iOS UITableView Cell 自适应高度 (Objective-C)
要使 UITableView 的 cell 自适应高度,可以使用以下步骤:
- 在 UITableViewDelegate 中实现以下方法:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// 返回你想要的行高
return UITableViewAutomaticDimension;
}
-
在 UITableViewCell 的子类中,使用 Auto Layout 来布局 cell 的子视图。确保子视图的约束设置正确。
-
在 UITableViewCell 的子类中,实现以下方法:
- (void)layoutSubviews {
[super layoutSubviews];
// 更新子视图的约束
[self.contentView layoutIfNeeded];
}
- (CGSize)sizeThatFits:(CGSize)size {
CGSize cellSize = [super sizeThatFits:size];
// 保证 cell 的宽度与 UITableView 的宽度一致
cellSize.width = size.width;
return cellSize;
}
以上步骤可以实现 UITableView 的 cell 自适应高度。
原文地址: https://www.cveoy.top/t/topic/qfY6 著作权归作者所有。请勿转载和采集!