cellForItemAtIndexPath

cellForItemAtIndexPath

我有一个UICollectionView,并且在每个单元格中,从数组中设置UILabelcellForItemAtIndexPath的文本:

let array = ["New York City", "Chicago", "San Francisco"]


单元格在屏幕上显示为正确标记,但是当我尝试在didSelectItemAtIndexPath中记录标签的值时,它将值记录为nil。如果我尝试在didSelectItemAtIndexPath中执行其他任何操作(例如更改单元格的不透明度),则不会执行任何更改。

这里可能出什么问题了?



相关代码:

视图控制器具有超类UICollectionViewDataSourceUICollectionViewDelegateFlowLayout

集合视图单元格的类声明:

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.
}

最佳答案

原来我犯了一个愚蠢的错误。在didSelectItemAtIndexPath中,我正在调用dequeueReusableCellWithReuseIdentifier,应该将其称为cellForItemAtIndexPath

08-15 19:34