【问题标题】:unexpectedly found nil while unwrapping an Optional values access tableView Cell在展开可选值访问 tableView 单元时意外发现 nil
【发布时间】:2016-02-03 08:58:43
【问题描述】:

我想从 tableView 函数外部访问 tableView 的单元格, 例如在这种情况下,我想从 IBAction Func 访问,然后我创建了 tableView 对象和 IndexPath 对象,当我运行我的项目时,Xcode 向我显示此错误:

致命错误:在展开可选值时意外发现 nil

对于这一行:mytableView!.cellForRowAtIndexPath(indexPath!)

@IBAction func editButtonFunc(sender: AnyObject) {

    mytableView!.cellForRowAtIndexPath(indexPath!)
    let cell =
    mytableView!.dequeueReusableCellWithIdentifier(
        "mycell", forIndexPath: indexPath!)
        as! profileTableViewCell
    cell.contentOutlet.text = contentItems[indexPath!.row]
    cell.contentOutlet.textAlignment = NSTextAlignment.Right
    cell.contentOutlet.font = UIFont(name: "X Yekan", size: 18)

}

【问题讨论】:

  • 你在哪里创建 indexPath?
  • 您不应该在此方法中使单元格出列。如果cellForRowAtIndexPath 返回 nil,则当前没有可用于该索引路径的单元格,您应该继续前进。

标签: ios swift tableview


【解决方案1】:

调用 tableview 方法 cellForRowAtIndexPath 几乎总是错误的。如果索引路径不是屏幕上可见的单元格,它将返回 nil。您的情况更糟,因为您调用该函数然后不使用它的值。绝对,完全错误的是从您自己的委托 cellForRowAtIndexPath 以外的任何地方调用 dequeue....。

【讨论】:

    【解决方案2】:

    当您尝试打开包装时,mytableViewindexPath 显然是 nil。在强制解包之前,您必须检查这两个对象的值是否正确。

    【讨论】:

      【解决方案3】:

      如果您只想获取某个单元格的 ref,也许您需要:

      func getTableViewCell() -> UITableViewCell? {
          guard let tableView = mytableView, index = indexPath 
          else { return nil }
      
          return tableView.cellForRowAtIndexPath(index)
      }
      

      而且,如果您想为 tableViewCell 设置数据,您应该在 UITableViewDataSource 方法中执行此操作:cellForRowAtIndexPath

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-23
        • 2016-10-18
        • 2017-04-09
        • 2018-09-22
        相关资源
        最近更新 更多