设为首页 加入收藏

TOP

iOS 学习 - 8.TableViewCell 自适应高度
2017-10-13 10:17:08 】 浏览:1338
Tags:iOS 学习 8.TableViewCell 适应 高度

思路:计算文字的高度,存进数组

加注:存在中文,需要加一行文字的高度,也就是 font

主要代码

#pragma mark -- UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSNumber *height = self.heightArray[indexPath.row];
    //含有中文需要加一行字体的高度,也就是 font
    return height.floatValue;
}
//存储计算出来的高度
- (NSMutableArray *)heightArray {
    if (!_heightArray) {        
        _heightArray = [NSMutableArray arrayWithCapacity:0];
        for (int i = 0; i < self.dataSource.count; i++) {
            NSString *str = [NSString stringWithFormat:@"%@",_dataSource[i]];
            CGFloat height = [HeightModel calculate:str];
            [_heightArray addObject:[NSNumber numberWithFloat:height]];
        }
    }
    return _heightArray;
}
//计算文字高度
+ (CGFloat)calculate:(NSString *)text {

    CGSize maxSize = CGSizeMake(KScreenWidth, MAXFLOAT);
    CGSize trueSize = [text boundingRectWithSize:maxSize
                                         options:
                       (NSStringDrawingUsesFontLeading | NSStringDrawingUsesLineFragmentOrigin)
                                      attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:15]}
                                         context:nil].size;
    NSLog(@"%f",trueSize.height);
    return trueSize.height+15;
}

 介绍一个类库:SDAutoLayout,比自己造的轮子好多了

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇学习ios【1】Objective-C 基本语法 下一篇archive(Error)

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目