Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide UITableViewCells while not violating AutoLayout constraints

I'm currently working on an app to learn iOS programming and Swift. I have a view which contains two main subviews, a MKMapView and a UITableView. When a certain annotation is selected in the MapView, I want certain cells in the TableView to be hidden. If the annotation is deselected the cells should reappear. Currently I do this by setting the height for the cells to be hidden to 0 and calling tableView.beginUpdates() tableView.endUpdates(), however this causes all kinds of AutoLayout constraints inside my custom cells to break. I've also tried to set the hidden property on the cell to true before setting the height to 0, but AutoLayout constraints are still being broken.

What would be the proper way to do this?

Thanks in advance.

like image 610
Lars Stegman Avatar asked Jul 29 '16 12:07

Lars Stegman


2 Answers

My 2 cents: just try to lower the priority of one of the conflicting constraints to a lower value, like UILayoutPriorityDefaultHigh (750 if used in Interface Builder) or even lower, it depends on how you cell is composed. It should be enough to give the auto layout system a hint about which constraint can be safely broken. Probably you will want to break the constraint that defines the distance from the bottom margin.

like image 174
Alessandro Orrù Avatar answered Oct 22 '22 22:10

Alessandro Orrù


Implementing heightForRowAtIndexPath: like below. also you need to set the height constraint to 0

Objc version

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (shouldHideCell)
        return 0;
    }
    else {
        return UITableViewAutomaticDimension;
    }
}

Swift version

     override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
  if shouldHideCell {
            return 0
        } else {
            return UITableViewAutomaticDimension
        }
  }
like image 1
Rajesh Avatar answered Oct 22 '22 23:10

Rajesh