【发布时间】:2018-02-08 14:29:54
【问题描述】:
这是我的代码。
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.row 。在上述方法中,编译器抱怨单元格为零。这一行:让 indexPath = tblJobs.indexPath(for: cell!)。
这段代码有什么问题。此代码中的单元格如何为零。谁能帮我解决这个问题?
【问题讨论】:
-
编译器不知道单元格是
nil。问题发生在运行时。 -
@Matt 好的,谢谢。关于等级制度还有另一种看法。我忘记了。 :) 让 cell = button?.superview?.superview?.superview 为! UITableViewCell ...这条线有效
-
优秀。我建议删除问题。
-
@Sptibo 不要导航单元格视图层次结构。它很脆弱。不要使用标签。它们很脆弱。设计一个合适的解决方案。 stackoverflow.com/questions/28659845/…
标签: ios swift uitableview cell