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

标签 ios uitableview autolayout uikit tableview

我想制作一个具有不同单元格大小和不同单元格内容的 UITableViewController

例如:

Example Storyboard

有没有办法在 Storyboard 中使用 AutoLayout 来定义 TableViewCells 的不同大小?定义 TableViewCells 的内容(带有内容的 UIView)的最佳方式是什么?

最佳答案

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

选项 A(最佳) 是使用具有自动布局约束的自动调整 TableView 单元格的大小。

要使用选项 A,您需要确保您的单元格内容 View 对内容 View 中的所有 UI 元素具有明确的顶部和底部约束(请在此处查看我的图片),例如:

Autosizing UITableViewCell

Title UILabel 与 superview (Cell ContentView) 的顶部空间和与 SubTitle 的垂直间距。 SubTitle 对 super View (Cell ContentView)也有底部空间限制。

这允许单元格自动调整大小,因为我的 UI 元素对内容 View 有顶部和底部约束。

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

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

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

选项 B 是添加 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath; 委托(delegate)给您的 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;
    }
}

关于ios - Storyboard中具有不同单元格大小和单元格内容的 UITableViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40606539/

相关文章:

ios - iPad 上的多个 UINavigationViewController

ios - 向 tableview 添加渐变会隐藏内容

ios - 如何在 iOS 中动态处理 tableviewCell 的高度?

swift - 动画约束 : Working on the "View as iPhone" in IB but not other iPhones

ios - 使用 AutoLayout( Storyboard)自动将 UIView 的高度调整为它的 subview

ios - 在 stroybord 检查器中使用方程编辑自动布局 "constant"属性

ios - performSelectorInBackground 和 detachNewThreadSelector 是如何工作的?

IOS 表情符号 unicode 列表

ios - 如何在一个 UIButton 中实现启动和停止操作?

ios - 如何在 UITableView 中启用/禁用滚动?