如何利用autolayout动态计算UITableViewCell的高度

2025-05-17 09:52:28
推荐回答(1个)
回答1:

实现上面的步骤其实很简单:
1.在Cell对应的xib文件中建立完整的约束。
2.使用[cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]方法对cell进行动态计算高度,
然后在方法- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath返回cell的高度。
注意:[cell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize]一定是cell.contentView,不能用cell。
相关代码:
- (void)viewDidLoad{
[super viewDidLoad];
_data = @[@"数据1", @"数据2",@"数据3", @"数据4", @"数据5", @"数据6"];
_tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
_tableView.delegate = self;
_tableView.dataSource = self;
[self.view addSubview:_tableView];
_cell = [[[NSBundle mainBundle] loadNibNamed:@"LWCell" owner:self options:nil] lastObject];
_textViewCell = [[[NSBundle mainBundle] loadNibNamed:@"LWTextViewCell" owner:self options:nil] lastObject];
_textViewCell.textView.delegate = self;
}