我有一个UICollectionView
,在每个单元格中,我从一个数组中设置UILabel
cellForItemAtIndexPath
的文本:
let array = ["New York City", "Chicago", "San Francisco"]
单元格在屏幕上显示正确标记,但当我尝试在didSelectItemAtIndexPath
中记录标签的值时,它会将值记录为nil
。如果我尝试在didSelectItemAtIndexPath
中执行任何其他操作(例如更改单元格的不透明度),则不会执行任何更改。
这里可能出现什么问题?
相关代码:
视图控制器具有超类UICollectionViewDataSource
和UICollectionViewDelegateFlowLayout
。
集合视图单元格的类声明:
class PickerCell: UICollectionViewCell {
var label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
contentView.backgroundColor = UIColor.clearColor()
label.frame = contentView.bounds
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Left
label.font = font.body
contentView.addSubview(label)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
创建集合视图:
func createPickerView() {
let pickerFlowLayout: UICollectionViewFlowLayout = PickerLocationFlowLayout()
pickerFlowLayout.itemSize = CGSize(width: screenSize.width, height: 40)
pickerFlowLayout.minimumLineSpacing = 0
let pickerView: UICollectionView
pickerView = UICollectionView(frame: CGRectMake(0, 0, screenSize.width, screenSize.height), collectionViewLayout: pickerFlowLayout)
pickerView.registerClass(PickerCell.self, forCellWithReuseIdentifier: "PickerCellId")
pickerView.delegate = self
pickerView.dataSource = self
self.view.addSubview(pickerView)
}
选择一个单元格:
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("PickerCellId", forIndexPath: indexPath) as! PickerCell
print("indexpath: \(indexPath.row), label: \(cell.label.text)")
// Prints the correct row number, but nil for the label.
}
答案 0 :(得分:0)
原来我犯了一个愚蠢的错误。在didSelectItemAtIndexPath
,我正在调用dequeueReusableCellWithReuseIdentifier
,我本应该调用cellForItemAtIndexPath
。