我正在使用IB和故事板,我定义了UITableViewController
。我在那里定义了三个静态单元格。前两个应该有一个给定的高度,但最后一个应该自动填充剩余的空间(锚到视图的底部)。我怎样才能做到这一点?我可以使用自动布局来控制内部单元格,但它对于单元格本身是灰色的。
最好的解决方案是从IB执行此操作,但也欢迎程序化解决方案。
修改
这就是它在我的故事板中的样子(颜色用于可视化单独的控件,每个控件都需要约束):
发布后:
请注意,文本视图在屏幕底部下方结束。
我忘了提到我的目标是iOS 7.0 +。
答案 0 :(得分:64)
您实际上可以将UITableViewAutomaticDimension
与静态单元格一起使用。按常规设计静态单元格,并通过添加
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 240 // Something reasonable to help ios render your cells
现在覆盖heightForRow
代理
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
我注意到这个技术的另一个警告是你必须使用NSAutolayout
来创建一个约束到底部容器(UITableViewCell
的容器)。所以,让我们假设你在单元格内容中有一个容器,它有一个动态高度,为了正确渲染你需要创建一个底部空间约束。
如果您有一些固定高度的静态单元格,我建议您通过启用tableView:heightForRowAtIndexPath:indexPath
中的行来返回该大小
答案 1 :(得分:11)
请务必覆盖heightForRowAtIndexPath!否则它将无法从我的经验中正确显示
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
return UITableViewAutomaticDimension
}
答案 2 :(得分:7)
好的,试试这个
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
if indexPath.row == 0 {
return firstRowHeight
}
else if indexPath.row == 1 {
return secondRowHeight
}
else {
return tableView.frame.size.height - firstRowHeight - secondRowHeight
}
}
唯一可能是问题的是这个方法将在视图设置tableView高度之前运行
答案 3 :(得分:4)
我在博客文章中使用静态表格视图并使用自动布局设置单元格高度。单元格都在界面构建器中定义。
您必须在代码中启用自动单元格高度,但这只是几行。
我展示了包括IB和代码在内的所有内容。
看看
http://www.oliverfoggin.com/using-a-static-uitableview-as-a-layout-device/
答案 4 :(得分:2)
如果整个tableview单元格高度是动态的,那么你可以尝试这个
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 240
或tableview需要一些固定高度的细胞和细胞。一些动态高度单元格,你可以检查答案 Dynamic & static tableview cell height
希望它有所帮助。
答案 5 :(得分:1)
不确定IB并使用Autolayout
但是以编程方式使用,
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
使用此方法,您可以检查indexpath.row。并使用它返回不同的高度。
答案 6 :(得分:1)
对于静态(非数据驱动)高度,您只需将单元格出列一次并存储高度:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSNumber *height;
if (!height) {
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"MyCustomCell"];
height = @(cell.bounds.size.height);
}
return [height floatValue];
}
答案 7 :(得分:1)
Ryan Romanchuk的回答很棒。我有一个小贴士可能会像我一样帮助初学者。
由于这是一个静态单元格案例,您可能倾向于对每个动态字段使用IBOutlet
。在UILabel
加载周期之外的tableView
设置值将不会考虑新的高度。
要允许动态高度起作用,您可以在覆盖的cellForRowAtIndexPath
委托中指定值,以便autolayout可以获取新的高度。如果要更新字段,请致电tableView.reloadData()
。