cellForRow(at: ) returns nil

sunny

So I have this function.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {  
    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
    changeCellProperty(selectedIndexPath: indexPath)
    return cell;
}

func changeCellProperty(selectedIndexPath: IndexPath){
    print("indexpath = \(selectedIndexPath)") . // printing [0,0] and all values
    let cell = self.tableView.cellForRow(at: selectedIndexPath) as! customCell    
    // got nil while unwrapping error in above statement.

    cell.label.text = ""
    // and change other properties of cell.
}

I am not able to understand the error. When I am getting the indexpath, then why I am not able to point a particular cell and change properties accordingly.

Rakesha Shastri

You cannot access a cell that has not yet been added to the tableView. That is what you are trying to do here in changeCellProperty method. So, if your dequeue works, then all you would need to do is pass the dequeued cell to that method.

func changeCellProperty(cell: customCell){
     cell.label.text = ""
     // and change other properties of cell.
}

Your cellForRowAt method would look like this.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cellIdentifier = "Cell"
    let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! customCell
    changeCellProperty(cell: cell)
    return cell
}

Note: class names should be UpperCamelCase. So your customCell should be named CustomCell.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related