Search code examples
iosswiftuitableviewnslayoutconstraint

Add NSLayoutContraint between UITableViewCell and UITableView


So, I want to add a constraint that enforce a maximum height on every cell to be smaller than or equal to 2/3 of the UITableView's height.

How can I achieve this?

Adding the constraint in func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell is not an option, since the cell is not in the UITableView, so it complains that they have no common superview.

So basically, how do I relate my UITableViewCells and my UITableView with NSLayoutContraints?


Solution

  • Well you can't do it like that. What you can do is get the height of the tableview and then add a height constraint on your cells of that amount. So in interface builder add a height constraint for your cell and set it to a convenient value (just to see what is in the table, it will be updated from code). Then add a reference in code for that constraint. Then in update the value of the constraint:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cellidentifier", forIndexPath: indexPath) as! YourCustomCell
        cell.heightConstraint.constant =  2.0 * tableview.frame.size.height / 3.0
    }
    

    This is if you are using dynamic size cells. Otherwise you could just override: func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat and return the size you want.