I have a collectionView with 2 sections, each section should be based off the same cell (which only contains a UIImageView). The only difference between the sections is the number of cells they should contain and types of images displayed.
If I set the cellforItemAtIndexPath method to use a dequeued cell (collectionView.dequeueReusableCellWithIdentifier) everything populates fine, if I set it to use an instance of my custom cell without dequeuing, it crashes.
cellForItemAtIndexPath method:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
//cannot use dequedReusableCell since some cells below scroll-line should remain highlighted
let cell = NumbersCollectionViewCell() // CAUSES CRASH
// let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.cellIdentifier, forIndexPath: indexPath) as! NumbersCollectionViewCell // WORKS FINE
switch indexPath.section {
case 0: cell.imageView.image = UIImage(named: numberImageFiles[indexPath.row])
case 1: cell.imageView.image = UIImage(named: specialNumberImageFiles[indexPath.row])
default: break
}
return cell
}
NumbersCollectionViewCell definition:
class NumbersCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
}
The error that appears is: "Fatal error: unexpectedly found nil while unwrapping an Optional value" and it highlights the "case 0" row in my cellForItemAtIndexPath method.
The reason I don't want to use a dequeued cell is that I need some of the cells to be highlighted at run-time based on user selections, and if I use a dequeued cell it doesn't seem to keep the ones below the scroll-line highlighted.
Assuming that you have both a .swift
and a .xib
file for your cell, you need to instantiate your NumbersCollectionViewCell
like this: Eg
let numbersCollectionViewCell = UINib(nibName: "NumbersCollectionViewCell", bundle: bundle).instantiateWithOwner(nil, options: nil)[0] as! NumbersCollectionViewCell
Otherwise, your IBOutlet
s will not be connected.
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier(identifier: "NumbersCollectionViewCell">, forIndexPath: NSIndexPath>) as? NumbersCollectionViewCell else {
print("failed to get cell")
return UICollectionViewCell()
}
switch indexPath.section {
case 0: cell.imageView.image = UIImage(named: numberImageFiles[indexPath.row])
case 1: cell.imageView.image = UIImage(named: specialNumberImageFiles[indexPath.row])
default: break
}
return cell
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.