Search code examples
iosxcodeautolayout

How to set contraints for self sizing UITableViewCell using Auto Layout in Interface Builder


I have a self-sizing tableViewCell that presents comments. If the current user commented I present edit and delete buttons. My contraints work perfectly in this case. All of my constraints are set in Interface Builder.

The challenge now is that when a comment doesn't belong to a user I set .isHidden = true for both the edit and delete buttons. How can I adjust my constraints for this new scenario?

enter image description here

EDIT: The issue is when I set .isHidden to true on the buttons, I want to cell height to shrink as the button space is empty.


Solution

  • Another approach:

    Toggle the .isActive state of the constraint from the bottom of the buttons to the bottom of the cell, along with the .isHidden state.

    To do so, add a vertical space constraint from the bottom of your date label to the bottom of the cell, set to >= 4 (or however much "padding" you want when the buttons are not there).

    Add an @IBOutlet for the spacing constraint from the bottom of the Edit button to the bottom of the cell. In your image, it shows as bottom = Edit Button.bottom + 2. When you ctrl+drag the constraint from IB to your source file it will generate the IBOutlet line like this:

    @IBOutlet weak var editButtonBottomConstraint: NSLayoutConstraint!
    

    You will need to edit that line, though... Constraints are deallocated when deactivated, unless you have a "strong" reference to it. So, simply remove the weak modifier:

    @IBOutlet var editButtonBottomConstraint: NSLayoutConstraint!
    

    Now, in cellForRowAt, you can do:

        cell.deleteButton.isHidden = !(comment.userID == appUserID)
        cell.editButton.isHidden = !(comment.userID == appUserID)
        cell.editButtonBottomConstraint.isActive = (comment.userID == appUserID)
    

    Although, personally, I would make that a function inside the cell.


    Based on your cell design, though, I'm guessing commentsLabel is possibly / probably a multi-line label? And you'll want the cell to expand vertically if the comment is, say, 8 lines long? If so, you still have a few constraint relationships to work out.