0

I have a label and an image.

if image != nil {
  cell height = 445
} else {
  //how do i set the cell height according to the label?
}
johnjay22113
  • 143
  • 1
  • 9

1 Answers1

1

You should set the height of tableView cells in heightForRowAt. This function returns the height of the cell for a given indexPath (as you probably have guessed). Inside there you can use return label.frame.height

In Swift 3:

override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if image != nil {
    return 445
  } else {
    return label.frame.height
  }
}

Edit: You can't use cellForRowAt until cells are initialized in cellForRowAt. So Try this instead. It assumes the image and label are @IBOutlets

Ike10
  • 1,535
  • 11
  • 13
  • It's not working... here is my tableview func: `func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell` – johnjay22113 Jun 18 '16 at 01:27
  • Please post your function in your question so it can be properly formatted. Also, are the label and image properties on a `UITableViewCell` subclass? If not, where are they declared? @johnjay22113 – Ike10 Jun 18 '16 at 01:30
  • @Ike10: `cellForRow(at:)` returns nil if the cell isn't visible or `indexPath` is out of range, however, calling `cellForRow(at:)` from inside `tableView(_:heightForRowAt:)` crashes the app (even if all cells have been initialized) due to some sort of odd recursive call of `tableView(_:heightForRowAt:)` - actually I don't fully understand this behavior. `tableView(_:cellForRowAt:)` doesn’t cause an error but I’d say as a method of `UITableViewDataSource` it’s not intended to be used in this way - do you agree on that? – Tobi Sep 28 '16 at 13:56