【问题标题】:UICollectionView delegate methods not being called properlyUICollectionView 委托方法没有被正确调用
【发布时间】:2016-02-28 01:50:07
【问题描述】:

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

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

【问题讨论】:

  • 你添加了collectionView.delegate和.dataSource = self吗?
  • 是的,如createPickerView()所示,delegate和dataSource确实设置为self

标签: swift uitableview uicollectionview uikit uicollectionviewcell


【解决方案1】:

原来我犯了一个愚蠢的错误。在didSelectItemAtIndexPath,我打电话给dequeueReusableCellWithReuseIdentifier,我应该叫cellForItemAtIndexPath

【讨论】:

    猜你喜欢
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 2020-11-28
    • 2017-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多