user2636197 user2636197 - 2 months ago 12
iOS Question

Select what cell class to use in didEndDisplaying

In my tableView I can toggle between two cell classes depending on layout. So now I wonder how I can choose what cell class to select in the

didEndDisplaying
function.

Should I choose cell by using
dequeueReusableCell
like in the function bellow?

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if isBigCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellBig") as! BigTableViewCell
cell.myImageView.kf.cancelDownloadTask()
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellSmall") as! SmallTableViewCell
cell.myImageView.kf.cancelDownloadTask()
}
}





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

if isBigCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellBig") as! BigTableViewCell

let data = ads[(indexPath as NSIndexPath).row]
cell.configureWithData(data)

//Dont show highlight
cell.selectionStyle = UITableViewCellSelectionStyle.none

return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "CellSmall") as! SmallTableViewCell

let data = ads[(indexPath as NSIndexPath).row]
cell.configureWithData(data)

//Dont show highlight
cell.selectionStyle = UITableViewCellSelectionStyle.none

return cell
}

}

Answer

The cell is given to you in the didEndDisplaying method. You determine its real type based on the indexPath, just like you did in the cellForRowAt method.

Do not dequeue another cell in didEndDisplaying. Just cast the provided cell based on the indexPath.

Since it seems that you don't use indexPath to determine then cell type, then your code should be something like this:

func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    if isBigCell {
        if let bigcell = cell as? BigTableViewCell {
            bigcell.myImageView.kf.cancelDownloadTask()
        }
    } else {
        if let smallcell = cell as? SmallTableViewCell {
            smallcell.myImageView.kf.cancelDownloadTask()
        }
    }
}