0
我有一个UICollectionView
,并且在每个单元中予设定的UILabel
的文本中,在cellForItemAtIndexPath
,从数组:UICollectionView委托方法没有被调用正确
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.
}
您是否添加了collectionView.delegate和.dataSource = self? – Lee
是的,如'createPickerView()'所示,委托和数据源确实设置为'self'。 –