我通过以下方式创建了单元格:
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/