David Park David Park - 3 months ago 8
Swift Question

Dynamic UITableViewCell Height with Exceptions

I am trying to dynamically set the height of my custom cell. I used the below code and it works.

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = view.frame.height / 4


However, I need my table view at index 0 (first cell) as a header with a fixed height and the rest of the cells to have dynamic height.

I tried this:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if indexPath.row == 0 {
return (self.view.frame.height/2)
}
return tableView.estimatedRowHeight
}


But that just sets the height to whatever I set estimatedRowHeight to in the viewDidLoad()

How can I make it so that the first row at index 0 has a height of 1/2 of the screen

view.frame.height / 2


while the rest of the cells changes height dynamically. Thank you for your help!

Answer

I think you need to return tableView.rowHeight instead of tableView.estimatedRowHeight from heightForRowAtIndexPath method for the cells whose indexPaths are greater than 0:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
  if indexPath.row == 0 {
    return (self.view.frame.height / 2)
  }
  return tableView.rowHeight // or return UITableViewAutomaticDimension
}
Comments