heightForRowAtIndexPath
永远不应该调用in cellForRowAtIndexPath
。
第一个在第二个之前调用,如果您需要访问标签(例如计算文本的高度),您通常可以初始化一个单元格。
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static CategorieCell *cell;
if (!cell) {
cell = [tableView dequeueReusableCellWithIdentifier:@"CellIdentifier"];
cell.frame = CGRectMake(0, 0, tableView.frame.size.width-tableView.contentInset.left-tableView.contentInset.right, cell.frame.size.height);
[cell layoutIfNeeded];
}
cell.label.text = myDatasourceText;
CGFloat cellHeight = ....
return cellHeight;
}
注意 1:
我dequeueReusableCellWithIdentifier
假设您使用的是 Interface Builder,否则您需要使用alloc] initWithStyle:...]
;
注意 2:
如您所见,我正在设置单元格的框架。这是必需的,否则您的单元格将(320 x 44)
作为默认值。相反,您可能在 iniPhone 6/6+ (i.e. screen width: 414)
或 in 中iPad
,您可能需要根据标签的宽度和文本计算标签的高度,因此您需要设置单元格的框架。
注意 3:
我假设您有一组相等的单元格结构,因此我正在使用一个static
单元格,因此它将被重用而不分配其他无用的单元格。