The Cook The Cook - 2 months ago 13
Swift Question

How to set set height of some cells manually when using UITableViewAutomaticDimension?

I am using UITableViewAutomaticDimension for setting heights of my UITableView cells. For a filter functionality, I need to hide some cells, and I am going to hide them by setting their height to 0.

However when I override heightForRowAtIndexPath, I need to return some value for the rows I wanna automatically sized too. How do I set it ?

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 50


,

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if shouldHideCell == true{
return 0
}else{
return automaticHeight // I need a value here!!!
}
}

Answer

In Your case try to set the UITableViewAutomaticDimension in the method rather than in your viewDidload like:

override func viewDidLoad() {
     super.viewDidLoad()
     tableView.estimatedRowHeight = 50
     ....
}


func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if shouldHideCell == true{
        return 0.0
    }else{
        return UITableViewAutomaticDimension
    }
}

I am hoping that you are using autoLayouts to work with UITableViewAutomaticDimension. And be aware that heightForRowAtIndex gets called before cellForRow method, so make sure your variable shouldHideCell is properly set before that.