Kirill Baranov Kirill Baranov - 25 days ago 11
Swift Question

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

enter image description here

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.

Answer

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
  5. If all is done correctly, this code should do the thing.

    @IBOutlet var hiddenConstaints: [NSLayoutConstraint] = []
    @IBOutlet var visibleConstaints: [NSLayoutConstraint] = []
    
    func hide(_ hide: Bool) {
    
        for hiddenConstaint in self.hiddenConstaints {
            hiddenConstaint.isActive = hide
        }
    
        for visibleConstaint in self.visibleConstaints {
            visibleConstaint.isActive = !hide
        }
    
        self.layoutIfNeeded()
    }
    

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

There is faster solution:

  1. Move content than 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

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

Comments