UITableView's Cell calculates height based on content

In daily development, we often encounter UITableView's cell that dynamically calculates its height according to the content inside. There are many ways to dynamically calculate its height. Here I will introduce one of them first. The application of this method is relatively simple. It is convenient and can realize the high self-adaptation of the cell faster

Create UITableView

1 Before creating UITableView, I created a data source array dataSourceArr by lazy loading, which stores some strings of different lengths to add to the cell to achieve different heights of the cell

2 Add UITableView, obey the data source

- (void)viewDidLoad {
    [super viewDidLoad];
    UITableView *mainTableView = [[UITableView alloc]initWithFrame:self.view.bounds];
    self.mainTableView = mainTableView;
    [self.view addSubview:mainTableView];
    self.mainTableView.dataSource = self;
}

3 Implement the two data source methods that must be implemented

// 返回每个区域中有几行cell
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSourceArr.count;
}
// 返回每个cell的样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"MainTableViewCell";
    MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[MainTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    NSString *testStr = self.dataSourceArr[indexPath.row];
    // 以下的两个赋值方法千万不能把顺序写反了,因为我们是根据其展示的内容计算的高度
    cell.testStr = testStr;
    tableView.rowHeight = cell.rowHeight;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

Where testStr is the string to be displayed in the UILabel in this row, and cell is the custom cell below. Here we save the height of each cell calculated according to different contents in the custom cell in the rowHeight property of the cell, and assign the height of each cell through tableView.rowHeight, so that we can return the data source method of the cell Assign a different desired height to each cell in

Customize UITableViewCell and calculate height based on content

1 Create the MainTableViewCell class, inherit from UITableViewCell, and customize the style of the cell. In this case, in order to show different heights, I only added a UILabel to it. In development, you can create different controls according to your own needs, and the principle of calculating height is the same.

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self configureCell];
    }
    return self;
}
// 创建自定义cell的内容控件
- (void)configureCell{
    UILabel *testLabel = [[UILabel alloc]init];
    self.testLabel = testLabel;
    [self addSubview:testLabel];
    testLabel.backgroundColor = [UIColor yellowColor];
    testLabel.font = [UIFont systemFontOfSize:16];
    testLabel.numberOfLines = 0;
}

2 Declare two properties in the .h file of this class, one to pass the string displayed in the UILabel and one to save the calculated height of each cell

@interface MainTableViewCell : UITableViewCell
// 保存每个cell的UILabel中展示的字符串
@property(copy,nonatomic)NSString *testStr;
// 保存计算出来的每个cell的高度
@property(assign,nonatomic)CGFloat rowHeight;
@end

3 Assign a value to each UILable by overriding the setter method of the assignment string, and calculate the height required by the UILabel

- (void)setTestStr:(NSString *)testStr{
    _testStr = testStr;
    self.testLabel.text = testStr;
    // 调用计算控件布局和cell高度的方法
    [self setupSubViewConstrainWithStr:testStr];
}
- (void)setupSubViewConstrainWithStr:(NSString *)testStr{
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    // 根据Label的内容计算所需要的高度,maxSize为控件的最大的宽高
    CGSize maxSize = CGSizeMake(width-20, CGFLOAT_MAX);
    CGRect rect = [testStr boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} context:nil];
    self.testLabel.frame = CGRectMake(10, 10, width-20, rect.size.height);
    // 如果此处有多个控件可以获取最后一个控件的最大Y值,也可以将里边的全部控件的高度加起来,之后保存到自己的rowHeight属性中
    // 此方法的核心就是在这里通过cell里边的控件计算出这个cell应有的高度,保存起来,然后在数据源方法中利用tableView.rowHeight方法为其赋值
    self.rowHeight = CGRectGetMaxY(self.testLabel.frame)+10;
}

Finally, different content cells show different heights, and the effect is as follows:
write picture description here

Summarize

There are other ways to dynamically calculate the height of the cell, such as the method of frameModel, the method of using the UITableView proxy to return the height of the cell, but I think this method is relatively simple and convenient to use in development, so I will give a brief introduction here. The core of which is the rowHeight property of UITableView.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326055322&siteId=291194637