Skip to content

Instantly share code, notes, and snippets.

@spanage
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spanage/aa2404c55373cefdf23d to your computer and use it in GitHub Desktop.
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).
// 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