iOS收集iOS开发入门iOS开发杂货铺

自适应TableViewCell(XIB)

2016-12-06  本文已影响2123人  PencilCarefully

前言:前一文自适应TableViewCell(纯代码)介绍了如何使用纯代码方式实现tableViewCell自适应高度,那么本文就来介绍一下如何使用XIB+Autolayout的方式实现tableViewCell的自适应高度.先看一下效果图,和上篇文章介绍的效果图是一样的.

图1.gif
#pragma mark - 懒加载
- (NSArray *)dataSource {
    if (!_dataSource) {
        self.dataSource = [AdaptiveModel mj_objectArrayWithFilename:@"ModelList.plist"];
    }
    return _dataSource;
}
图2.png

需要注意: 要设置text_Labellines是0,否则不会自动换行.

图3.png
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
 
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStylePlain];
//    [self.tableView registerClass:[AdaptiveTableViewCell class] forCellReuseIdentifier:identifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"AdaptiveTableViewCell" bundle:nil] forCellReuseIdentifier:@"AdaptiveCell"];
    
    // self-sizing(iOS8以后才支持)
    // 设置tableView所有的cell的真实高度是自动计算的(根据设置的约束)
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    // 设置tableView的估算高度
    self.tableView.estimatedRowHeight = 200;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    
}

需要注意:tableView的估算高度,可以给一个随意的值,只要是大于0的就可以.建议给这个值给的稍微大一点,这里面牵扯到tableView性能优化的一些东西.

// 设置单元格
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AdaptiveTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AdaptiveCell" forIndexPath:indexPath];
    // 传递数组模型
    cell.model = self.dataSource[indexPath.row];
    return cell;
}
@interface AdaptiveTableViewCell ()

@property (weak, nonatomic) IBOutlet UILabel *nameLabel; // 姓名
@property (weak, nonatomic) IBOutlet UILabel *text_Label; // 正文
@property (weak, nonatomic) IBOutlet UIImageView *picthreView; // 图片

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pictureHeight; // 图片高度约束
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *pictureBottom; // 图片底部约束

@end
// 重写setter方法
- (void)setModel:(AdaptiveModel *)model {
    if (_model != model) {
        _model = model;
    }
    
    self.nameLabel.text = model.name;
    self.text_Label.text = model.text;
    
    if (model.picture) { // 有图片
        self.picthreView.hidden = NO;
        self.picthreView.image = [UIImage imageNamed:model.picture];
        self.pictureHeight.constant = 100;
        self.pictureBottom.constant = 10;
    } else { // 没有图片
        self.picthreView.hidden = YES;
        self.pictureHeight.constant = 0;
        self.pictureBottom.constant = 0;
    }
}

需要注意:在没有图片时候需要把图片的约束更改为0,在有图片的时候也一定要把约束更改回来,否则因为tableViewCell的循环引用,界面滑动的时候,会造成显示混乱.

总结:到这里我们就把自适应TableViewCell的功能实现了.对比来说,使用AutoLayout方式要比使用纯代码的方式更加简单一些.不需要再去计算控件的高度这些繁琐的步骤,只有几个注意事项需要多注意.避免不必要的错误.

另附本文gitHub地址

上一篇:自适应TableViewCell(纯代码)

上一篇 下一篇

猜你喜欢

热点阅读