自定义UICollectionViewCell上的标签插座在Swift中导致Optional.None崩溃 [英] Label Outlet On Custom UICollectionViewCell In Swift Causing Optional.None Crash
问题描述
我有一个collectionViewController,我想显示一堆自定义的UICollectionViewCells,上面有一些标签。不幸的是,每当我尝试访问自定义UICollectionViewCell的标签时,都会导致崩溃:
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:
控制台
致命错误:无法打开Optional.None
fatal error: Can't unwrap Optional.None
窗口
Thread1:EXC_BAD_INSTRUCTION(代码= EXC_1386_INVOP,子代码= 0x0)
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)
}
}
推荐答案
找到答案这里
删除, self.collectionView.registerClass(MyCustomCollectionViewCell.self,forCellWithReuseIdentifier:reuseIdentifier)
阅读链接了解
这篇关于自定义UICollectionViewCell上的标签插座在Swift中导致Optional.None崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!