Search code examples
iosswiftuitableviewconstraintsdynamic-resizing

How to get resizing tableView cell with different content without deleting constraints in iOS


I have tableView cell with different content(views, labels, imageViews) in one cell. But in something cells content can be not full. How can i use resizing cells without removing and adding always constraints? Thanks.

illustration of the problem


Solution

  • One of possible solutions for this problem:

    1. Add constraints for hidden state with priority 1000
    2. Add extra constraints for resized state with lower priority (ex 750)
    3. Save constraints that is ONLY for hidden state into IBOutlet collection
    4. Save constraints that is ONLY for resized state into another IBOutlet collection

    Code:

    @IBOutlet var hiddenConstraints: [NSLayoutConstraint] = []
    @IBOutlet var visibleConstraints: [NSLayoutConstraint] = []
    
    func hide(_ hide: Bool) {
    
        for hiddenConstraint in self.hiddenConstraints {
            hiddenConstraint.isActive = hide
        }
    
        for visibleConstraint in self.visibleConstraints {
            visibleConstraint.isActive = !hide
        }
    
        self.layoutIfNeeded()
    }
    

    There is faster solution:

    1. Move content that can be hidden into container view
    2. Set height constraint for container view
    3. Change from code height constraint constant to 0 if hidden or to proper height if visible

    Code:

    @IBOutlet var heightConstraint: NSLayoutConstraint!
    
    func hide(_ hide: Bool) {
    
        self. heightConstraint.constant = hide ? 0 : 150  //Estimated height
    
        self.layoutIfNeeded()
    }
    

    This is not a good approach, as it will lead to constraint crashes at runtime. So I prefer to use first one.

    Also you will need to update your cell from table to move other cells up or down.