利用iOS8新特性计算cell的实际高度

在计算cell的实际高度是 我们一般是通过计算frame  拿到最底部一个控件的最大Y值从而的到cell 的高度  算来算去  比较麻烦  

其实,iOS8已经提供了直接通过Cell高度自适应的方法了,根本不用计算Cell高度,就可以搞定不等高Cell  这个方法即对系统cell有效 也对通多xib创建的cell有效:
 
方法:设置tableView的估算Cell高度&rowHeight值为自动计算模式
    self.tableView.estimatedRowHeight = 100;  //  随便设个不那么离谱的值
    self.tableView.rowHeight = UITableViewAutomaticDimension;

注意:::不能实现heightForRow代理方法!

代码:

#import "TESTTableViewController.h"
#import "TESTTableViewCell.h"
@interface TESTTableViewController ()
@property (nonatomic,strong) NSArray *contentAry;
@end

@implementation TESTTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.estimatedRowHeight = 100;  //  随便设个不那么离谱的值
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.contentAry = @[@"哈哈哈",@"哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈",@"啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈",@"哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈"];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell";
    
    //利用系统自带cell类型
//    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
//    if (cell == nil) {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
//        
//    }
//    cell.textLabel.numberOfLines = 0;
//    cell.textLabel.text = self.contentAry[indexPath.row];
//    return cell;
    
    //通过xib构建cell
    TESTTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        NSArray *nibs = [[NSBundle mainBundle]loadNibNamed:@"TESTTableViewCell" owner:nil options:nil];
        cell = [nibs firstObject];
    }
    cell.contentText.numberOfLines = 0;
    cell.contentText.text = self.contentAry[indexPath.row];
    return cell;
}
@end

效果图:

通过xib创建的cell:                                                

系统自带cell类型:

参考资料:简书  demo(提取码:a75d)

原文地址:https://www.cnblogs.com/gaoxiaoniu/p/5341408.html