As the title states, I have a label in a UICollectionReusableView. The view I use is dequeued successfully using the following:
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
let hourCell = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier:"Hour", forIndexPath: indexPath) as! HourCollectionReuseableView;
let time = String(indexPath.item) + "H";
hourCell.setTime(time);
return hourCell;
}
Here is the Interface builder view of HourCollectionReuseableView
. I note here that I do this in the custom class of file owner:
Here is the Collection Reuse Identifier:
Here is the HourCollectionReuseableView
class:
class HourCollectionReuseableView: UICollectionReusableView {
@IBOutlet weak var hourLabel: UILabel!
@IBOutlet weak var hourDividerLine: UIView!
override func awakeFromNib() {
super.awakeFromNib();
}
func setTime(time:String) {
self.hourLabel.text = time;
}
In my view controller I register the class as follows:
override func viewDidLoad() {
super.viewDidLoad();
self.collectionView.registerClass(HourCollectionReuseableView.self, forSupplementaryViewOfKind: "Hour", withReuseIdentifier:"Hour");
}
The code keeps crashing on self.hourLabel.text = time
with the following error:
fatal error: unexpectedly found nil while unwrapping an Optional value
Where am I going wrong?
Just as @firstinq pointed out, as you're working with a .xib
in your HourCollectionReuseableView
, you should try using registerNib
instead of registerClass
.
So, you're code should look more like
override func viewDidLoad() {
super.viewDidLoad();
self.collectionView.registerNib(UINib(nibName: "HourCollectionReuseableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Hour");
}
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