Last active
August 29, 2015 14:19
-
-
Save spanage/aa2404c55373cefdf23d to your computer and use it in GitHub Desktop.
This code fixes layout issues with UITableViews that contain cells dynamically sizing labels in them (when using UITableViewAutomaticDimension).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// To be placed in your UITableViewDelegate. | |
// | |
// This is doing what autolayout *should* be doing which using the constraints to determine cell | |
// height as needed. Currently, even with correctly setting prefferedMaxLayoutWidth on | |
// labels within cells, heights calculated correctly at all times. | |
// If you use this you MUST call dequeueReusableCellWithIdentifier, NOT | |
// dequeueReusableCellWithIdentifier:atIndexPath in your cellForRow:atIndexPath method. | |
// Otherwise you will crash. Again - this is a HACK and not good iOS dev. | |
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { | |
let contentView: UIView = tableView.dataSource!.tableView(tableView, cellForRowAtIndexPath: indexPath) | |
contentView.updateConstraintsIfNeeded() | |
contentView.layoutIfNeeded() | |
return contentView.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize).height | |
} | |
// To be placed in each cell containing labels with dynamic height | |
override func layoutSubviews() { | |
super.layoutSubviews() | |
// Assuming 2 labels with dynamic height in my cell: myLabelA and myLabelB | |
myLabelA.preferredMaxLayoutWidth = myLabelA.bounds.width | |
myLabelB.preferredMaxLayoutWidth = myLabelB.bounds.width | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment