Reputation: 1289
I have a UICollectionView in Storyboard, in a UICollectionViewController. The UICollectionViewController is linked to my custom class MasterViewController: UICollectionViewController, UICollectionViewDataSource, UICollectionViewDelegate
, and it's delegate and datasource are linked in the storyboard to this class.
I have a prototype UICollectionViewCell in storyboard, with an identifier "MyCell", from my custom class Cell: UICollectionViewCell
In the cellForItemAtIndexPath
method, the app crash at the line : let cell:Cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as Cell
I don't find why. I haven't implemented the registerClass:forCellWithReuseIdentifier:
method, and the identifier of the storyboard is exactly "MyCell", I checked many times, and the delegate and datasource are linked to the right class.
When the app crash, nothing is printed in the console, just "(lldb)"
Here's my code :
class MasterViewController: UICollectionViewController,UICollectionViewDataSource,UICollectionViewDelegate {
var objects = [ObjectsEntry]()
@IBOutlet var flowLayout: UICollectionViewFlowLayout!
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
flowLayout.itemSize = CGSizeMake(collectionView!.bounds.width - 52, 151)
}
// MARK: - Collection View
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return objects.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell:Cell = collectionView.dequeueReusableCellWithReuseIdentifier("MyCell", forIndexPath: indexPath) as Cell
return cell
}
Upvotes: 5
Views: 5764
Reputation: 4517
I had the same problem. Raywenderlich Swift manual helped me. I copying MyCollectionViewController
here.
UICollectionViewCell
class.UICollectionViewCell
in Storyboard.viewDidLoad()
. registerClass:forCellWithReuseIdentifier:
Set cell item size with UICollectionViewDelegateFlowLayout
in collectionView:layout:sizeForItemAtIndexPath:
.
import UIKit
class MyCollectionViewController:
UICollectionViewController,
UICollectionViewDelegateFlowLayout {
private let reuseIdentifier = "ApplesCell"
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView,
cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as MyCollectionViewCell
cell.backgroundColor = UIColor.redColor()
cell.imageView.image = UIImage(named: "red_apple")
return cell
}
Upvotes: 5