分享

iOS8 UITableView动态加载cell的高度

 爽行天下丶 2015-06-19

iOS8 UITableView动态加载cell的高度

iOS8新特性,ios8以后,你在也不需要根据cell上内容的不一样计算每个cell的高度了,因为系统可以自己加载它的高度。下面是具体的实现代码:

@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>

// 数据源
@property (nonatomic, strong) NSMutableArray *dataArray;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // 设置一个默认的值
    _tableView.rowHeight = UITableViewAutomaticDimension;
    // 这个高度可以随便设置,可以是 44 或者其他数
    _tableView.estimatedRowHeight = 4;
    
    _dataArray =[NSMutableArray arrayWithCapacity:0] ;
    [_dataArray addObjectsFromArray:@[@"1",@"2",@"3",@"了一个激动人心的特性,UITableView 的 Self Sizing Cells。对于开发者来",@"在iOS8中,苹果给出了一个激动人心的特性,UITableView 的 Self Sizing Cells。对于开发者来说,这是一个很值得一试的特性,在iOS8以前,如果需要在UITableViewCell中展示动态的内容,必须每次计算内容所占高度,然后赋值给UITableView的height。在iOS8中,苹果给出了一个激动人心的特性,UITableView 的 Self Sizing Cells。对于开发者来说,这是一个很值得一试的特性,在iOS8以前,如果需要在UITableViewCell中展示动态的内容,必须每次计算内容所占高度,然后赋值给UITableView的height。"]];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.textLabel.text = _dataArray[indexPath.row];
    cell.textLabel.numberOfLines = 0;
    return cell;
}


运行结果:高度系统自动帮算好了



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多