1

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:

enter image description here

the_critic
  • 12,720
  • 19
  • 67
  • 115
  • If you are targeting iOS 8 or later, you would be much better off using Auto Layout to constrain your label to your cell, and use automatic height to size your cell properly. – Mike Taverne Oct 21 '15 at 04:45
  • See answer titled "For iOS 8 - Self-Sizing Cells" here: http://stackoverflow.com/questions/18746929/using-auto-layout-in-uitableview-for-dynamic-cell-layouts-variable-row-heights/18746930#18746930 – Mike Taverne Oct 21 '15 at 04:48
  • @MikeTaverne I also have to target iOS7... – the_critic Oct 21 '15 at 11:46
  • That's a bummer. That post also has a solution for iOS 7 that might help you. – Mike Taverne Oct 21 '15 at 13:38

0 Answers0