UItableviewCell 自动设置Cell高度(UITableViewAutomaticDimension)

我们之前在tableview中,经常要设置行高,如果设置了一个固定的高度,就达不到“数据驱动UI”了效果了。接下来,我写了一个demo,看看效果:

ViewController:

#import "ViewController.h"
#import "TestCell.h"
#import "TestModel.h"
@interface ViewController ()
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *arrayData;
@end
static NSString *testCellId = @"TestCell";

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupTableView];
    
    [self loadData];
    
}

- (void)loadData {
    for (int i = 0;  i < 4; i ++) {
        TestModel *model = [[TestModel alloc]init];
        model.strTitle = [NSString stringWithFormat:@"%dtitle",i];
        model.strDesc = [NSString stringWithFormat:@"%ddesc",i];
        [self.arrayData addObject:model];
    }
    [self.tableView reloadData];
}

- (void)setupTableView {
    UITableView *tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:0];
    [self.view addSubview:tableView];
    self.tableView = tableView;
    tableView.delegate = self;
    tableView.dataSource = self;
    
    //registerId
    [tableView registerClass:[TestCell class] forCellReuseIdentifier:testCellId];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TestCell *cell = [tableView dequeueReusableCellWithIdentifier:testCellId forIndexPath:indexPath];
    cell.model = self.arrayData[indexPath.row];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}


- (NSMutableArray *)arrayData {
    if (!_arrayData) {
        _arrayData = [[NSMutableArray alloc] init];
    }
    return _arrayData;
}

@end

TestModel.h

@interface TestModel : NSObject
@property (nonatomic, copy) NSString *strTitle;
@property (nonatomic, copy) NSString *strDesc;
@end

TestCell.h

@class TestModel;

@interface TestCell : UITableViewCell
@property (nonatomic, strong) TestModel *model;
@end

TestCell.m

#import "TestCell.h"
#import "TestModel.h"
#import "Masonry/Masonry.h"
@implementation TestCell

- (void)setModel:(TestModel *)model {
    _model = model;
    [self.contentView.subviews performSelector:@selector(removeFromSuperview)];
    UILabel *lbl = [[UILabel alloc]init];
    lbl.text = model.strTitle;
    [self.contentView addSubview:lbl];
    
    [lbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.contentView);
        make.top.mas_equalTo(self.contentView).offset(50);
        make.left.mas_equalTo(self.contentView).offset(15);
    }];
}

配合masonry布局,实现了cell高度自适应。

你可能感兴趣的:(OC)