David Seek David Seek - 2 months ago 7
Swift Question

Swift / How to avoid, that UITableView rowHeight changes unwanted

I have a UITableViewController with dynamic cells and different sections. Once the controller is getting called, the rowHeigths are perfect. Then I'm moving to another controller (within another rootViewController) - completely off context and strings of the UITableViewController.

Once I go back to the UITableViewController, viewDidLoad will not be called anymore. That is fine.
But all the cells are having the same size (I'd say 44, what is the basic row height).

Is there any possibility to avoid this behavior?

This is my code and it is the only time the rowHeight is set:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

if indexPath.section == 0 {
tableView.rowHeight = 125

let cell = tableView.dequeueReusableCellWithIdentifier("bla") as! bla
return cell
}

if indexPath.section == 1 {
tableView.rowHeight = 80

let cell = tableView.dequeueReusableCellWithIdentifier("bla") as! bla
return cell
}

if indexPath.section == 2 {
tableView.rowHeight = 50

let cell = tableView.dequeueReusableCellWithIdentifier("bla") as! bla
return cell

}

if indexPath.section == 3 {
tableView.rowHeight = 60

let cell = tableView.dequeueReusableCellWithIdentifier("bla") as! bla
return cell
}

if indexPath.section == 4 {
tableView.rowHeight = 450

let cell = tableView.dequeueReusableCellWithIdentifier("bla") as! bla
return cell

}

return UITableViewCell()
}

Answer

You should implement the heightForRowAtIndexPath method for setting different cell height in same tableview.

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat
{
    var cellHeight : CGFloat = 44.0
    switch indexPath.section
    {
        case 0: cellHeight  = 125.0
        case 1: cellHeight  = 80.0
        case 2: cellHeight  = 50.0
        case 3: cellHeight  = 60.0
        case 4: cellHeight  = 450.0
        default: cellHeight = 44.0 
    }
    return cellHeight
}