我的代码中出现NSInternalInconsistencyException错误

时间:2017-09-20 04:08:20

标签: ios swift uicollectionview

以下是我的代码:

import UIKit

class FriendsController: UICollectionViewController {

    private let cellId = "cellId"

    override func viewDidLoad() {
        super.viewDidLoad()

        collectionView?.backgroundColor = UIColor.red

        collectionView?.register(FriendCell.self, forCellWithReuseIdentifier: cellId)
    }

    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int)  -> Int{
        return 3
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell{
        return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath)
    }

    }

    class FriendCell: UICollectionViewCell {

    override init(frame: CGRect) {

        super.init(frame: frame)
        setUpViews()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    func setUpViews() {
        backgroundColor = UIColor.blue
    }
}

以下是我的错误:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', 
reason: 'the collection view's data source did not return a valid cell from 
-collectionView:cellForItemAtIndexPath: for index path 
<NSIndexPath: 0xc000000000000016> {length = 2, path = 0 - 0}'

我不确定我做错了什么?如果有人可以帮助解释我的错误以及如何解决它,那将非常感激。我对Swift来说还是有点新鲜,这是我第一次错误理解,特别是在我的代码环境中。

1 个答案:

答案 0 :(得分:1)

您使用较旧的Swift 2 API作为数据源方法。

而不是:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath as IndexPath)
}

使用:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    return collectionView.dequeueReusableCell(withReuseIdentifier: cellId, for: indexPath)
}