我想做什么:
在 UITableViewController 方法 heightForRowAtIndexPath 中,我想推断行高的值,而不是硬编码。
我在“界面”构建器中的故事板中设置了之前的值。
错误的方法:
以下方法是错误的方法,因为它是在创建实际单元格之前调用的,因此它会循环:
// wrong approach
- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
//AppTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AppCel" forIndexPath:indexPath];
//int height = cell.frame.size.height;
// TODO: Make it more dynamic
return 112;
}
方法我在考虑:
有没有办法加载单元格 main.storyboard 文档并推断高度值?还是有其他方法吗?
相关问题搜索:
我发现以下unanswered related question可以追溯到2010年。This other问题没有多大用处,因为它从单元格内容而不是故事板文档中获得了高度。
答案 0 :(得分:3)
您编码的方法实际上并非完全错误。有什么问题是使用dequeueReusableCellWithIdentifier:forIndexPath
。相反,您希望使用更简单的版本dequeueReusableCellWithIdentifier
,您可以使用它来提供原型单元格,您可以配置,布局然后计算高度。
如果使用纯粹的iOS8,所有这些都是通过新的自动布局完成的。如果您也想支持iOS7,那么您需要手动执行此操作。
以下链接说明了您需要使用的过程。我使用它,当你想同时支持iOS7和iOS8时它很有用。
Using Auto Layout in UITableView for dynamic cell layouts & variable row heights
你还必须注意你是否在你的单元格中使用基于大小类的约束,因为你必须解决一个不太明显的问题才能使高度正确。见Offscreen UITableViewCells (for size calculations) not respecting size class?
答案 1 :(得分:0)
答案 2 :(得分:0)
如果你有一个xib(CP_Cell.xib)中的单元格,你可以这样做:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return ((CP_Cell *) [[NSBundle mainBundle] loadNibNamed:@"CP_Cell" owner:self options:nil].lastObject).frame.size.height;
}