使用情节提要吗?。实例化会返回“意外发现nil”错误

时间:2019-04-09 09:41:19

标签: ios swift xcode

使用storyboard?.instantiate时出现错误。这给了我这个错误:

  

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

这是我的代码:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let vc = storyboard?.instantiateViewController(withIdentifier: "SelectedViewController") 
             as? SelectedViewController
    vc?.name = imgArr[indexPath.row]
    self.navigationController?.pushViewController(vc!, animated: true)
}

并且我已经在这张照片中使用了标识符ID

go to the photo from here

请任何人都可以帮助我解决此问题。

3 个答案:

答案 0 :(得分:0)

将鼠标移到IB中的类字段上,然后单击Enter,必须勾选模块检查,并确认您正确设置了情节提要标识符

enter image description here

答案 1 :(得分:0)

SelectedViewController是否与集合视图的视图控制器位于同一个情节提要中?

我总是喜欢用防护罩打开可选组件,或者尽量避免此类崩溃。您可以使用:

   guard let viewController = storyboard?.instantiateViewController(withIdentifier: "SelectedViewController") as? SelectedViewController else { "return error here if wanted" return }
    viewController.name = imgArr[indexPath.row]
    self.navigationController?.pushViewController(viewController, animated: true)

答案 2 :(得分:0)

请尝试以下代码:

let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vcTitles =  storyBoard.instantiateViewController(withIdentifier: "vcTitles") as! VCTitlesViewController
self.navigationController?.pushViewController(vcTitles, animated: true)