How to hide UITableViewCells while not violating AutoLayout constraints

非 Y 不嫁゛ 提交于 2019-12-22 04:56:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!