ios - fatal error : unexpectedly found nil while unwrapping an Optional values

标签 ios swift uicollectionview

我在 Swift 中使用了 UICollectionView,但是当我尝试更改单元格标签的文本时,我得到了。

    func collectionView(collectionView: UICollectionView!, numberOfItemsInSection section: Int) -> Int
{
    return 5
}

func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell!
{
    var cell = collectionView.dequeueReusableCellWithReuseIdentifier("title", forIndexPath: indexPath) as TitleCollectionViewCell
    // Next line: fatal error: unexpectedly found nil while unwrapping an Optional value
    cell.labelTitle.text = "This is a title"
    return cell
}

有人知道这个吗?

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

最佳答案

您可以通过使用 if let 语句安全地解包 cell.labelTitle 来防止崩溃发生。

if let label = cell.labelTitle{
    label.text = "This is a title"
}

您仍然需要进行一些调试才能了解为什么您会得到一个 nil 值。

关于ios - fatal error : unexpectedly found nil while unwrapping an Optional values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43017451/

相关文章:

ios - 通过模态消除呈现的模态

ios - App进入后台判断当前ViewController

swift - 如何滚动循环CollectionView

ios - UICollectionView 什么时候请求它的数据?

ios - iOS 上的 processing.org, native

ios - 在继续之前强制运行 Realm 通知 block

ios - 在 IOS 中显示一个新 View

ios - NSURLSession:无法与后台传输服务通信

swift - 在 Swift 问题中使用 Firebase 查询中的数据

objective-c - 如何一次加载 UICollectionView 的所有单元格?