I have a collectionViewController that I want to display a bunch of custom UICollectionViewCells with some labels on them. Unfortunately whenever I try and access the custom UICollectionViewCell's label it causes a crash with:
Console
fatal error: Can't unwrap Optional.None
Window
Thread1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)
I'm trying to access the label like so:
cell.name.text = names[indexPath!.item]
Perhaps this comes from my outlet label being nil? But looking around for answers nothing has worked, and because I'm not really sure what the issue is adding ?/! in my code isn't really helping.
MyCustomUICollectionViewController
class ScrambledTextCollectionViewController: UICollectionViewController {
var names: String[] = ["Anna", "Alex", "Brian", "Jack"]
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView.registerClass(MyCustomCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func numberOfSectionsInCollectionView(collectionView: UICollectionView?) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView?, numberOfItemsInSection section: Int) -> Int {
return names.count
}
override func collectionView(collectionView: UICollectionView?, cellForItemAtIndexPath indexPath: NSIndexPath?) -> UICollectionViewCell? {
var cell = collectionView?.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as MyCustomCollectionViewCell
cell.name.text = names[indexPath!.item]
return cell
}
}
MyCustomCollectionViewCell
class MyCustomCollectionViewCell: UICollectionViewCell {
@IBOutlet var name: UILabel
init(frame: CGRect) {
super.init(frame: frame)
}
}
Found the answer here
Remove, self.collectionView.registerClass(MyCustomCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
Read link for detailed reason why
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With