我有一个collectionViewController,想要展示一堆带有标签的自定义UICollectionViewCells。不幸的是,每当我试图访问自定义UICollectionViewCell的标签时,会引起崩溃,并显示以下信息:
控制台
"fatal error: Can't unwrap Optional.None"
窗口
"Thread1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)"
我尝试这样访问标签:
控制台
"fatal error: Can't unwrap Optional.None"
窗口
"Thread1: EXC_BAD_INSTRUCTION (code=EXC_1386_INVOP, subcode=0x0)"
我尝试这样访问标签:
cell.name.text = names[indexPath!.item]
也许这是因为我的插座标签为空?但是寻找答案时,没有任何有效的方法,而且由于我不确定问题所在,因此在我的代码中添加?/!并不能真正帮助解决问题。
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)
}
}
viewDidLoad
的范围之外定义var names
。你应该在整个对象的范围内定义变量var names
,而不仅仅是在viewDidLoad
中。 - Fogmeister