这是我的代码。
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))")
}
我正在从Web获取数据并将其填充在TableView上,一切正常。我想打印IndexPath。按下单元格上的按钮时。在上面的方法上,编译器抱怨细胞为零。此行:让IndexPath = tbljobs.indexpath(用于:Cell!(。
此代码有什么问题。该代码中的单元格是如何零的。谁能帮助我解决这个问题?
问题是当当前不可见单元格时,它的值是零,您无法明确解开可选值
let cell = button?.superview?.superview as? UITableViewCell
尝试这个
if(cell != nil)
{
let indexPath = tblJobs.indexPath(for: cell!)
}
旁边的单元格是CellAvailableJobs
,您使用as? UITableViewCell
行 let cell = button?.superview?.superview as? UITableViewCell
似乎是UITableViewCell
实例,因此cell
是nil
。
正如您发现的那样,这实际上是您想要的:
let cell = button?.superview?.superview?.superview as? UITableViewCell