2017-09-20 3 views
0

Voici mon code:erreur NSInternalInconsistencyException dans mon code

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 
    } 
} 

Et ce qui suit est mon erreur:

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}' 

Je ne suis pas sûr de ce que je fait de mal? Si quelqu'un pouvait m'aider à expliquer mon erreur et comment la résoudre, ce serait très apprécié. Je suis encore un peu nouveau chez Swift, et c'est ma première erreur que j'ai eu du mal à comprendre, surtout dans le contexte de mon code.

+0

Vous devez fournir les méthodes de source de données Swift 3, et non les méthodes Swift 2. – rmaddy

+0

Qu'entendez-vous par là? Comme je l'ai dit, je suis nouveau à Swift. –

Répondre

1

Vous utilisez l'ancienne API Swift 2 pour les méthodes de source de données.

Au lieu de:

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

Utilisation:

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

A travaillé! Merci beaucoup :) –