简体   繁体   中英

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.

However, despite calling both those methods in cellForRowAtIndexPath, when I check the frames of the subviews in the contentView, their frames are still incorrect. I've ensured to call layoutIfNeeded on each subview as well.

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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