Fatal error: unexpectedly found nil while unwrappi

2018-12-31 14:47发布

I was using an UICollectionView in Swift but I get when I try to change the text of the cell's label.

    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
}

Does anyone know about this?

Screenshot for warning on Console

13条回答
孤独寂梦人
2楼-- · 2018-12-31 15:24

Check if the cell is being registered with self.collectionView.registerClass(cellClass: AnyClass?, forCellWithReuseIdentifier identifier: String). If so, then remove that line of code.

See this answer for more info: Why is UICollectionViewCell's outlet nil?

"If you are using a storyboard you don't want to call this. It will overwrite what you have in your storyboard."

查看更多
宁负流年不负卿
3楼-- · 2018-12-31 15:27

fatal error: unexpectedly found nil while unwrapping an Optional value

  1. Check the IBOutlet collection , because this error will have chance to unconnected uielement object usage.

:) hopes it will help for some struggled people .

查看更多
余生无你
4楼-- · 2018-12-31 15:27

I had the same problem on Xcode 7.3. My solution was to make sure my cells had the correct reuse identifiers. Under the table view section set the table view cell to the corresponding identifier name you are using in the program, make sure they match.

查看更多
刘海飞了
5楼-- · 2018-12-31 15:27

I was having the same issue and the reason for it was because I was trying to load a UIImage with the wrong name. Double-check .setImage(UIImage(named: "-name-" calls and make sure the name is correct.

查看更多
柔情千种
6楼-- · 2018-12-31 15:30

Nil Coalescing Operator can be used as well.

rowName = rowName != nil ?rowName!.stringFromCamelCase():""
查看更多
回忆,回不去的记忆
7楼-- · 2018-12-31 15:32

I got his error when i was trying to access UILabel. I forgot to connect the UILabel to IBOutlet in Storyboard and that was causing the app to crash with this error!!

查看更多
登录 后发表回答