我有一个 collectionViewController,我想显示一堆带有一些标签的自定义 UICollectionViewCells。不幸的是,每当我尝试访问自定义 UICollectionViewCell 的标签时,它都会导致崩溃:
Console
致命错误:无法解开Optional.None
Window
线程1:EXC_BAD_INSTRUCTION(代码= EXC_1386_INVOP,子代码= 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
}
}
我的自定义集合视图单元格
class MyCustomCollectionViewCell: UICollectionViewCell {
@IBOutlet var name: UILabel
init(frame: CGRect) {
super.init(frame: frame)
}
}