ios - UITableViewCell 何时何地完成布局?

标签 ios swift uitableview layout

我通过以下方式创建了单元格:

cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier1)

我知道默认的初始化大小是(320,44)。我设置的高度是80.0

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

所以问题是单元格何时布局(从 44 变为 80)? 即使我调用了 layoutIfNeeded

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       if cell == nil {
            cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: identifier1)
       }
        print(cell.frame) // (0,0,320,44)
        cell.layoutIfNeeded()
        cell.setNeedsLayout()
        print(cell.frame) // still (0,0,320,44)

        return cell 
}

最佳答案

由于您在创建单元格后立即打印 cell.frame,它采用默认高度 44。它会在呈现表格时使用 heightForRowAtIndexPath 的高度.

当您调用 setNeedsLayout 时,它会设置一个标志,并且更改将在下一个渲染周期中渲染。您不能期望它会立即反射(reflect)在下一个语句中。

来自 Apple 文档:

Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews. This method makes a note of the request and returns immediately. Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance.

关于ios - UITableViewCell 何时何地完成布局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35329195/

相关文章:

ios - 如何在 Xcode 中创建 Entitlement.plist 文件?

ios - 如何更改 TableView 单元格文本标签颜色

ios - 将 JSON 解析为 TableView 时出现 NSNull 长度错误

swift - 表格 View 的API,添加数值和添加列,每10秒刷新一次表格

ios - 只需轻轻一按即可激活垂直分页

ios - UIWebView 缓存不工作

ios - UITableview 原型(prototype)单元格未正确填充

swift - 为什么 Int.random() 比 arc4random_uniform() 慢?

ios - 在 UIViewController 之间传递 UILongPressGestureRecognizer

xcode - 如何快速制作静音和取消静音按钮?