I have a UITableViewCell
with a label inside of it. I would like to calculate the cell size based on the contents inside of it.
I don't just set constraints in the content view though, I also add constraints to the enclosing UITableViewCell:
+--------------------------+
|UITableViewCell |
| | inset |
| +------------------+ |
| |contentView | |
| | |inset | |
| | +------------+ | |
|-- |--| Label |--| --|
| | +------------+ | |
| | |inset | |
| +------------------+ |
| |inset |
+--------------------------+
And here is the code that calculates the size:
override public class func cellSize(item: ItemInterface?, fittingSize: CGSize) -> CGSize {
struct Static {
static var onceToken : dispatch_once_t = 0
static var sizingCell : LabelTableViewCell!
}
dispatch_once(&Static.onceToken, {
Static.sizingCell = NSBundle.mainBundle().loadNibNamed("LabelTableViewCell", owner: self, options: nil)[0] as! LabelTableViewCell
})
let sizingCell = Static.sizingCell
// sets the text of the label and also adds constraints
// from label to enclosing content view
sizingCell.setupCell(text: "asdkfjklsd")
// for multi line support
sizingCell.label.preferredMaxLayoutWidth = fittingSize.width
// update all the constraints
sizingCell.setNeedsUpdateConstraints()
sizingCell.updateConstraintsIfNeeded()
// re-layout cell
sizingCell.setNeedsLayout()
sizingCell.layoutIfNeeded()
// calculate size for the whole cell (not just contentView)
let size = sizingCell.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
return CGSizeMake(size.width, size.height)
}
What I end up getting is a cell that is squished. The label ends up being too small and therefore you almost don't see the label at all: