【问题标题】:Compiler is complaining that cell is nil when I try to get indexpath.row when button is tapped on cell当我在单元格上点击按钮时尝试获取 indexpath.row 时,编译器抱怨单元格为零
【发布时间】: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


【解决方案1】:

问题是当单元格当前不可见时,它的值为 nil ,您无法显式解开可选值

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

试试这个

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

单元格类型旁边是CellAvailableJobs,您使用as? UITableViewCell

【讨论】:

  • @Sh_Khan 但是当我点击单元格按钮时它崩溃了。这意味着单元格是可见的。还是不行?
  • 单元格为零。我也应用了 guard let 语句..它可以防止应用程序崩溃,但我无法获取 indexpath.row
  • 你在哪里添加它??桌子上方?
【解决方案2】:

let cell = button?.superview?.superview as? UITableViewCell 行似乎不是UITableViewCell 实例,因此cellnil

如你所见,这实际上就是你想要的:

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

【讨论】:

  • @Sptibo 显示您的层次结构如何将按钮添加到单元格
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-21
  • 2022-11-24
  • 1970-01-01
相关资源
最近更新 更多