Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Label in UICollectionReusableView always nil

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:

enter image description here

Here is the Collection Reuse Identifier:

enter image description here

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?

like image 662
user481610 Avatar asked Aug 31 '16 12:08

user481610


1 Answers

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");
}
like image 54
blastervla Avatar answered Nov 03 '22 17:11

blastervla