swift UITableView set rowHeight

tim_yng picture tim_yng · Sep 2, 2014 · Viewed 143k times · Source

I am trying to set the height of each row in the tableView to the height of the corresponding cell with this code:

override func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat {
      var cell = tableView.cellForRowAtIndexPath(indexPath)
      return cell.frame.height
}

I get this error when initialising var cell :

Thread 1:EXC_BAD_ACCESS(code=2,address=0x306d2c)

Answer

Nagarjun picture Nagarjun · Aug 6, 2015

For setting row height there is separate method:

For Swift 3

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100.0;//Choose your custom row height
}

Older Swift uses

func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    return 100.0;//Choose your custom row height
}

Otherwise you can set row height using:

self.tableView.rowHeight = 44.0

In ViewDidLoad.