我有一个带有自定义表格 View 单元格的表格 View 。它们的高度取决于将出现在单元格中的文本量。这是我的 UITableViewDelegate 方法 heightForRowAtIndexPath 的代码:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = [indexPath row];
NSDictionary *factor = [self.factorsArray objectAtIndex:row];
CGSize maximumLabelSize = CGSizeMake(260, kMaximumFactorLabelHeight);
CGSize labelSize = [[factor objectForKey:@"text"] sizeWithFont:[UIFont fontWithName:@"Arial-BoldMT" size:14.0]
constrainedToSize:maximumLabelSize
lineBreakMode:UILineBreakModeWordWrap];
return (labelSize.height + 72);
}
此代码完美运行。我的问题是这里有很多东西是硬编码的:
- 表格 View 单元格中标签的宽度
- 字体名称
- 字体大小
- “72”是除标签高度外还需要添加到单元格的额外高度。
我可以从包含自定义表格 View 单元格的 xib 文件中获取所有这些信息。但是如何在 heightForRowAtIndexPath: 中获取它?我试过 - (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath 但我遇到了崩溃,我相信是因为调用 heightForRowAtIndexPath 方法时单元格尚不存在。
最佳答案
有几种方法可以做到这一点。我通常在 UITableViewCell 子类上有一个类方法来根据传入的内容返回高度。
关于ios - 在 UITableViewDelegate 方法 heightForRowAtIndexPath 中获取 TableView 单元格属性 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9363614/