在Storyboard中具有不同单元大小和单元格内容的UITableViewController

我想要使​​用不同的单元格大小和不同的单元格内容的UITableViewController

例如:

示例故事板

AutoLayoutStoryboard使用AutoLayout的方式来定义TableViewCells的不同大小? 定义TableViewCells的内容(包含内容的UIView )的最好方法是什么?

要更改UITableView的单元格,您有两个选项:

选项A(最好)是使用Autolayout Constraints Autosizing TableView单元格。

要使用选项A,您需要确保您的单元格contentview对内容视图中的所有UI元素(请参阅此处的图像)具有明确的顶部和底部约束作为示例:

自动调整UITableViewCell

标题UILabel有超级视图的顶部空间(Cell ContentView)和与SubTitle的垂直间距。 SubTitle对superview(Cell ContentView)也有一个底部空间约束。

这允许单元格被自动化,因为我的UI元素对内容视图有顶部和底部限制。

启用自动调整的最后一步是在UITableView中设置这两个属性:

 self.tableView.estimatedRowHeight = 60.0; self.tableView.rowHeight = UITableViewAutomaticDimension; 

estimatedRowHeight值应该尽可能接近真实的大小,这有助于加快计算速度。

选项B是添加- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; 委托给你的UIViewController。

你应该手动提供单元格的高度。 如果您只使用2个不同的单元格,并且具有2个固定的高度,那么您也可以使用选项B,然后添加一个逻辑来检测单元格并返回高度。

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; if ([cell isKindOfClass:[MyCustomCellTypeAClass class]]) { return 44; } else { return 100; } } 

如果你正在使用自动布局,高度将使用约束(如果你正确设置)计算; 你必须使用委托方法如下 –

 func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } 

使用故事板? 你的意思是这样吗? 在这里input图像描述

也许我应该提供一个演示(StackOverFlowQuestions02)来清除。 欲了解更多详情—>链接:

https://github.com/tingxins/StackOverFlowQuestions

我相信,运行演示,你会得到它。