cell自定义高度

2016-08-26  本文已影响0人  ios_stand
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    //取出模型
    
    XMGTopic *topic = self.topics[indexPath.row];
    
    CGFloat textY = 55;
    
    //根据文本宽度算出模型中text的高度
    
    CGFloat textH = [topic.text boundingRectWithSize:CGSizeMake(self.view.frame.size.width-40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;
    
    return textH+textY+44+10+10;
    
}

//开发中,不建议在- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath方法中计算每行cell的高度(每次滑动后都要重新计算当前展示cell的高度),建议在模型.h中去增加一个属性:

/** cell的高度*/
@property (nonatomic, assign) CGFloat cellHeight;

.m实现cellHeight的get方法

- (CGFloat)cellHeight

{
    
    if (!_cellHeight) {
        
        CGFloat textY = 55;
        
        CGFloat textH = [self.text boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 40, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:14]} context:nil].size.height;
        
        _cellHeight = textH+textY+44+10+10;
        
    }
    
    return _cellHeight;
    
}

//然后在tableview代理方法中实现:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{
    
    //取出模型
    
    XMGTopic *topic = self.topics[indexPath.row];
    
    return topic.cellHeight;
    
}

这样做的好处是把cell的高度存在模型中,不用每次都重新计算

上一篇下一篇

猜你喜欢

热点阅读