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
}

有人知道吗?

Screenshot for warning on Console

最佳答案

您可以通过使用 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/24643522/

相关文章:

swift - NSSharingService 不会编译归档

swift - 为什么我不能将 UICollectionViewCell 向下转换为它的子类?

arrays - 在 Swift 中从 Firebase 填充的多维数组

ios - UICollectionView 布局更改的默认动画持续时间是多少?

ios - 以编程方式更改 Y 位置约束

swift - 轻松截断 Double - swift

ios - 我的游戏中应该有多少个 View Controller ?

ios - 如何正确地阻止 UIButton 一段时间

ios - CGImageAlphaInfo.Last 在 iOS 8 中不受支持的参数组合

ios - 通过标签将照片从 Instagram 返回到我的 ios 应用程序