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

断了今生、忘了曾经 提交于 2019-12-04 11:13:54

问题


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)                
    }
}

回答1:


Found the answer here

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

Read link for detailed reason why



来源:https://stackoverflow.com/questions/24492275/label-outlet-on-custom-uicollectionviewcell-in-swift-causing-optional-none-crash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!