Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Label Outlet On Custom UICollectionViewCell In Swift Causing Optional.None Crash

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)                
    }
}
like image 728
William Robinson Avatar asked Jun 30 '14 14:06

William Robinson


1 Answers

Found the answer here

Remove, self.collectionView.registerClass(MyCustomCollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)

Read link for detailed reason why

like image 123
DogCoffee Avatar answered Nov 16 '22 14:11

DogCoffee