问题
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.
回答1:
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.
回答2:
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
}
}
来源:https://stackoverflow.com/questions/38659001/how-to-hide-uitableviewcells-while-not-violating-autolayout-constraints