Set table view cell height by identifier - Swift

Viewed 1225

I am trying to set the height of each cell in the table view depending on the identifier. I do not want to use indexPath.row, because the i am filling the cell from an array containing a flag for each type of cell and the order is random. Exactly 3 types of cells.

I used this code but it causing an error:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    let cell = tableV.cellForRow(at: indexPath)
    if(cell?.reuseIdentifier == "homeFeaturedR"){
        return 200
    }else{
       return 360
    }
}

The error is at this line:

let cell = tableV.cellForRow(at: indexPath)

Thank you.

4 Answers

Your heightForRowAt method is called before cellForRowAt. This means that by the time heightForRowAt is called, the cell at that index path is not yet created. Therefore, you can't access its reuseIdentifier or anything like that.

This means that instead of trying to figure out what height to return by looking at the cell, you should try to figure out the height using your model.

Dynamic table views ought to have a datasource/model. Your table view should have one as well. Look at your cellForRowAtIndexPath method, under what conditions do you dequeue a cell with the identifier homeFeatureR? It is most likely an if statement checking something:

if someCondition {
    let cell = tableView.dequeueReusableCell(withIdentifier: "homeFeatureR")!
    // set properties
    return cell
}

Now, you can just check if someCondition is true, if it is true, that means the cell's identifier must be "homeFeatureR", which means you should return 200.

if someCondition {
    return 200
} else {
    return 360
}

talking about UITableView lifecycle

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat

it's called before

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell

hence I guess your

func cellForRow(at indexPath: IndexPath) -> UITableViewCell?

returns nil

Seem like you wrong when select the tableView. You using the tableV not a tableView inside the function heightForRowAt indexPath. Let's change that and try again even this isn't a best ways in my mind.

First duque cell

    let cell = tableView.dequeueReusableCellWithIdentifier("CellIdentifier", forIndexPath: indexPath) as UITableViewCell

after that set cell height as you like.

Related