【问题标题】:Divide UITableView into fixed number of cells将 UITableView 划分为固定数量的单元格
【发布时间】:2015-11-25 23:10:43
【问题描述】:

我创建了一个 UIViewController,它有一个标题并包含一个 UITableView。现在我想将 UITableView 的整个高度划分为 6 个单元格。我用tableView.frame.size.height 尝试过,然后设置tableView.rowHeight = tableViewHeight / 6。但是当我启动应用程序时,表格视图的底部仍然有一些空间。 还有其他方法吗?

【问题讨论】:

  • 我假设您正在使用自动布局?
  • 是的,我在表格中添加了 4 个约束,所以它填满了整个空间。
  • 想一想,如果您在viewDidLoad: 中访问tableView.frame.size.height,那么它可能不会返回您期望的高度,因为视图尚未布局。跨度>
  • 等等——你想要 6 个还是 7 个单元格?标题与问题不符。
  • 对不起,实际上是 6。但似乎有人已经修好了。

标签: ios swift uitableview


【解决方案1】:

我建议从tableView:heightForRowAtIndexPath: 委托方法返回单元格高度,如下所示:

let numOfRows = 7

...

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return numOfRows
}

...

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return tableView.frame.size.height / CGFloat(numOfRows)
}

使用该方法,您可以直接访问您的tableView,您可以在其中将其高度除以所需的行数。返回该值以设置 tableView 的行高。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-22
    • 2017-11-21
    • 1970-01-01
    • 2021-09-18
    相关资源
    最近更新 更多