gpt4 book ai didi

swift - UICollectionView 委托(delegate)方法未正确调用

转载 作者:行者123 更新时间:2023-11-30 13:40:06 25 4
gpt4 key购买 nike

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

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

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

这里可能出了什么问题?

<小时/>

相关代码:

View Controller 具有父类(super class)UICollectionViewDataSourceUICollectionViewDelegateFlowLayout

Collection View 单元格的类声明:

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

创建 Collection View :

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

关于swift - UICollectionView 委托(delegate)方法未正确调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35677780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com