【发布时间】:2025-11-27 12:05:01
【问题描述】:
所以,heightForRowAtIndexPath 似乎在 cellForRowAtIndexPath 之前被调用。我目前正在使用cellForRowAtIndexPath 来计算每个单元格的高度(它们是可变高度,使用带有不同数量文本的UILabel。
如果在计算方法之前调用设置高度的方法,我不知道如何正确设置单元格的高度。 p>
我创建了一个NSString 类别和另一个UILabel 类别,它们共同使UILabel 大小合适。问题是包含这些标签的 UITableViewCell 实例未调整大小,因此标签挂在每个标签的末端,与下面的标签重叠。
我知道我需要做的是使单元格的高度等于标签的高度,加上一些额外的边距空间,但我很困惑如何在标签高度之前设置高度计算出来的。我可以在不使用heightForRowAtIndexPath 的情况下设置某人的高度吗?或者如果没有,我可以计算其他地方的单元格的高度吗?我目前正在使用indexPath.row 来实现这一点,所以事先这样做会很棘手。这是我的 cellForRowAtIndexPath 的代码:
cellForRowAtIndexPath
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
FQCustomCell *_customCell = [tableView dequeueReusableCellWithIdentifier: @"CustomCell"];
if (_customCell == nil) {
_customCell = [[FQCustomCell alloc] initWithStyle: UITableViewCellStyleValue1 reuseIdentifier: @"CustomCell"];
}
_customCell.myLabel.text = [[_loadedNames objectAtIndex: indexPath.row] name];
_customCell.myLabel.font = [UIFont fontWithName: @"FontA" size: 15.0f];
UIView *backView = [[UIView alloc] initWithFrame: CGRectZero];
backView.backgroundColor = [UIColor clearColor];
_customCell.backgroundView = backView;
_customCell.myLabel.frame = CGRectMake(5, 5, 265, 65);
[_customCell.myLabel sizeToFitMultipleLines];
return _customCell;
}
【问题讨论】:
-
从 iOS 8 开始,您还可以使用自动计算的动态行高。 *.com/questions/18746929/…
标签: ios objective-c uitableview