【问题标题】:It crashes in cellforrowatindexpath of tableview , says : "fatal error: unexpectedly found nil while unwrapping an Optional value"它在 tableview 的 cellforrowatindexpath 中崩溃,说:“致命错误:在展开可选值时意外发现 nil”
【发布时间】:2017-04-06 07:07:58
【问题描述】:

我在同一个 Collectionviewcell 上有两个 tableview。当我运行应用程序时,它在 tableview 的 cellforrowatindexpath 中崩溃,说:“致命错误:在展开可选值时意外发现 nil”

请在下面找到我的一些代码 -

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> 
UITableViewCell {

let cell = collectionView.dequeueReusableCell(withReuseIdentifier:     
reuseIdentifier, for: indexPathOfCollectionView as IndexPath) as!   
MyCustomCollectionViewCell

if(tableView == cell.graphTableView){

let cell:CustomGraphTableViewCell =   
tableView.dequeueReusableCell(withIdentifier: "CustomGraphTableViewCell") as!    
CustomGraphTableViewCell

return cell
    }
    else
    {
        let cell:MyCustomTableViewCell = 
 tableView.dequeueReusableCell(withIdentifier: "MyCustomTableViewCell") as!   
 MyCustomTableViewCell
        cell.nameLabel.text = namesArray[indexPath.row]
        return cell

    }
}

任何人都可以提出解决方案。为什么会发生这种情况?解决方法是什么?

【问题讨论】:

  • 你不能让CollectionViewCell`` in TableView cellForRowAt`方法出队。
  • 你在这里强制解开“as!”检查您的所有单元格,因为现在它为零
  • @NiravD 如果我不在那里声明collectionview单元格,那么我该如何访问tableview?
  • @Vadim Kozak 好的。如果它为零,我该怎么做才能纠正它?
  • 为什么你使用collectionview cell 而不是tableview cell? collectionview 单元格不能在 tableview 中作为单元格工作。

标签: ios iphone swift uitableview swift3


【解决方案1】:

在tableview中UICollectionViewCell不起作用,UICollectionViewCell是从UICollectionReusableView继承的不同类,UITableViewCell是从UICollectionViewCell不同的类,它是从UIViewNSCoding继承的,UIGestureRecognizerDelegate,所以在这里,您必须为您的表格视图仅使用 uitableview 单元格。否则会崩溃。

当你的 tableview 委托方法返回一些值不是 null 或 0 时,tableview 的数据源方法将执行,这意味着当你的 tableview 的委托方法有一些值时

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> 
UITableViewCell 

上面的方法现在将开始执行,当它找到时

let cell = collectionView.dequeueReusableCell(withReuseIdentifier:     
reuseIdentifier, for: indexPathOfCollectionView as IndexPath) as!   
MyCustomCollectionViewCell

上面的语句,它会崩溃。

这是

let cell:MyCustomTableViewCell = 
 tableView.dequeueReusableCell(withIdentifier: "MyCustomTableViewCell") as!   
 MyCustomTableViewCell
        cell.nameLabel.text = namesArray[indexPath.row]
        return cell

只将这条语句放在cellforRow数据源方法下,它会相应地工作。

谢谢

【讨论】:

  • 感谢阿布舍克!是的,我从 cellforrowatindexpath 中删除了 collectionviewcell 对象,并将标签分配给 tableview 进行检查,现在它工作正常:)
  • 太好了,:) 快乐编码,如果我的建议对你有用,请接受并投票给我的答案。谢谢 :)
【解决方案2】:

请检查这一行

cell.nameLabel.text = namesArray[indexPath.row]

cell.nameLabel 总是接受字符串值,首先转换成这样的字符串值:

cell.nameLabel.text = namesArray[indexPath.row] as NSString

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-26
    相关资源
    最近更新 更多