简体   繁体   English

iOS表格视图单元格动态尺寸-LayoutSubviews

[英]iOS Table View Cell Dynamic Size - LayoutSubviews

I'm trying to call [cell layoutIfNeeded] and [cell.contentView layoutIfNeeded] as I have a number of subviews that have custom constraint logic that I implement in the cell's layoutSubviews method. 我试图调用[cell layoutIfNeeded]和[cell.contentView layoutIfNeeded],因为我有许多子视图,这些子视图具有在单元的layoutSubviews方法中实现的自定义约束逻辑。

However, despite calling both those methods in cellForRowAtIndexPath, when I check the frames of the subviews in the contentView, their frames are still incorrect. 但是,尽管在cellForRowAtIndexPath中调用了这两个方法,但是当我在contentView中检查子视图的框架时,它们的框架仍然不正确。 I've ensured to call layoutIfNeeded on each subview as well. 我确保也可以在每个子视图上调用layoutIfNeeded。

Any ideas on why this is happening? 为什么会这样? The frames are only correct after the cell is displayed, but the height isn't being calculated properly before that. 框架仅在显示单元格之后才是正确的,但是在此之前,高度的计算不正确。

edit: 编辑:

I am trying to use the new auto size feature in iOS 8. It's not resizing properly because I have some complicated logic in terms of where my labels go if one is larger than the other. 我正在尝试使用iOS 8中的新自动尺寸调整功能。它的大小无法正确调整,因为如果一个标签的尺寸大于另一个标签,我的标签去向有些复杂的逻辑。 It's not as simple as stacking the labels together - which is why I need the subviews to be laid out correctly before the height is calculated. 这并不像将标签堆叠在一起那么简单-这就是为什么我需要在计算高度之前正确放置子视图。

I'm not sure what is happening with the code without more information but you should consider using Auto resizing cells. 我不确定在没有更多信息的情况下代码会发生什么,但是您应该考虑使用自动调整单元格大小。 This will resize your cells automatically without having to deal with layout subviews. 这将自动调整单元格的大小,而无需处理布局子视图。

override func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100
}

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

The layout subviews solution is still used in some edge cases but was mainly used before UITableViewAutomaticDimension came out. 布局子视图解决方案仍在某些情况下使用,但主要在UITableViewAutomaticDimension出现之前使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM