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?
答案 0 :(得分:5)
就像@firstinq指出的那样,当你在.xib
中使用HourCollectionReuseableView
时,你应该尝试使用registerNib
代替registerClass
。< / p>
因此,您的代码看起来应该更像
override func viewDidLoad() {
super.viewDidLoad();
self.collectionView.registerNib(UINib(nibName: "HourCollectionReuseableView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "Hour");
}