-2

Here is my code.

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: CellAvailableJobs = self.tblJobs.dequeueReusableCell(withIdentifier: "CellAvailableJobs") as! CellAvailableJobs
    let jobsNearByObj:JobsNearBy = self.jobsArray![indexPath.row]
    cell.loadCell(jobsNearByObj: jobsNearByObj)
    cell.btnHeart.addTarget(self, action: #selector(JobsVC.btnBookmarkAction), for: .touchUpInside)
    cell.btnHeart.tag = indexPath.row
    return cell
}

@IBAction func btnBookmarkAction(_ sender: AnyObject){
    let button = sender as? UIButton
    print("tag: \(String(describing: button?.tag))")
    let cell = button?.superview?.superview as? UITableViewCell
    let indexPath = tblJobs.indexPath(for: cell!)
    print("bookmarkedJobId: \(String(describing: indexPath.row))")
}

I'm fetching data from web and populating them on tableview, everything is working well. I want to print indexpath.row when the button on cell is tapped. On above method the compiler is complaining that the cell is nil. This line: let indexPath = tblJobs.indexPath(for: cell!).

What is the problem with this code. How the cell is nil in this code. Can anyone help me with this issue?

Sptibo
  • 281
  • 2
  • 8
  • 22
  • The _compiler_ knows nothing of the cell being `nil`. The problem occurs at runtime. – matt Feb 08 '18 at 14:34
  • @Matt ok thank you. there was another view on hierarchy. I forgot that. :) let cell = button?.superview?.superview?.superview as! UITableViewCell ...this line works – Sptibo Feb 08 '18 at 14:46
  • 2
    Excellent. I suggest deleting the question. – matt Feb 08 '18 at 14:48
  • @Sptibo Don't navigate the cell view hierarchy. It is fragile. Don't use tags. They are fragile. Engineer a proper solution. https://stackoverflow.com/questions/28659845/swift-how-to-get-the-indexpath-row-when-a-button-in-a-cell-is-tapped/38941510#38941510 – Paulw11 Feb 08 '18 at 19:48

2 Answers2

0

The problem is when cell is currently not visible it's value is nil , you can't explicitly unwrap an optional value

let cell = button?.superview?.superview as? UITableViewCell

Try this

 if(cell != nil)
{
   let indexPath = tblJobs.indexPath(for: cell!)
}

beside type of cell is CellAvailableJobs and you use as? UITableViewCell

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
0

Line let cell = button?.superview?.superview as? UITableViewCell seems to fail to be the UITableViewCell instance, thus cell is nil.

As you figured out, this is what you wanted in fact:

let cell = button?.superview?.superview?.superview as? UITableViewCell
Milan Nosáľ
  • 19,169
  • 4
  • 55
  • 90