Search code examples
iosxcodeuitableviewautolayout

Unable to set the height of a prototype cell as a constraint in storyboard


How does one add a constraint for the height of a prototype cell using a storyboard?

In the first screenshot below, I used the storyboard's "Reset to Selected Constraints" to automatically set them based on the canvas. I tried it both at the view controller level and also at the view level(s). But the result was the same in every case - it only added the few constraints as can be seen in the screenshot and when the code is run the blue cell displays with a height which is the same as the red one).

enter image description here

If I now try to add an additional explicit constraint for the height of the cells it won't let me - the option is greyed out.

If I delete all the constraints and try and add them manually, the option to add them is still disabled - why is that? See screenshot below for an example. Instead of selecting the headerCall as in the screenshot if I instead select Content View to set the constraints its the same, i.e. ability set them is disabled.

I'm just trying to add prototype cells where one type represents a section header which is narrow and another type represents a data content cell which is wider, but code's not making it obvious why I can't. (I don't have similar issues setting constrains with any of the other view controllers/views, just these prototype cells).

There is no code in the view controller setting any heights or constraints etc. Its virtually empty, I created it just to recreate the issue.

enter image description here


Solution

  • Actually constraints shouldn't be applied directly to content view of UITableViewCell as they already act as dynamic wrapper and adjust their height according to their subviews.

    Try adding a subview to content view and set a height constraint to that subview. And at the same time pin all sides of your new subview to content view.

    If you expect a static height from cell, then please override below code and make your viewController implement UITableViewDelegate:

    override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat
    

    Or if you want your cell height to be calculated from height constraints you just applied to subview of content view, in that case use:

     self.tableView.rowHeight = UITableViewAutomaticDimension;