gpt4 book ai didi

ios - 如何将值传递给自定义 UICollectionViewCell?

转载 作者:行者123 更新时间:2023-11-28 10:19:00 26 4
gpt4 key购买 nike

我有一个自定义的 UICollectionViewCell,我试图从我的 View Controller 向其传递一个值。我能够将图像传递给单元格,但初始化时其他任何内容都为零。

View Controller中的相关代码:

override func viewDidLoad() {

self.collectionView!.registerClass(MyCustomCell.self, forCellWithReuseIdentifier: "Cell")

}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MyCustomCell

cell.someValue = 5
cell.imageView.image = UIImage(named: "placeholder.png")

return cell

}

在自定义单元类中:

var someValue: Int!
var imageView: UIImageView!

override init(frame: CGRect) {

super.init(frame: frame)

imageView = UIImageView(frame: CGRectMake(0, 0, frame.width, frame.height))
contentView.addSubview(imageView)

let someValueLabel = UILabel()
someValueLabel.frame = CGRectMake(0, 75, 200, 30)
someValueLabel.text = "Value is: \(someValue)"
self.addSubview(someValueLabel)
}

图像已从 UICollectionView 成功传递,我可以显示它,但“someValue”始终为零。

我做错了什么?

最佳答案

init 方法的调用时间比您想象的要早得多——在dequeue 过程中——当单元格对象被构造时。初始化过程的一部分是附加在 Storyboard 中设计的 UIViews。所以该图像有效,因为 UIImageView 在 Storyboard (NIB) 加载过程中已经作为容器就位,您只需稍后设置其内部图像属性。

您已正确设置 someValue 的值以供所有 future 在单元格渲染和事件处理期间使用。因此,例如,如果有一个在单元格显示和点击后运行的 @IBAction 处理程序,它确实可以访问 someValue。那就是你的测试打印应该去的地方。您最终使用 someValue 的目的是什么?

跟进

所以这是一个简单的错误;您只需要在 cellForRowAtIndexPath 中设置文本值。您也不需要单元格中的模型数据副本(即您的单元格中不需要 someValue 字段)。只需根据您的(正确分离的)模型数据动态配置 UI:

代替:

cell.someValue = 5

你只需要,例如:

cell.someValueLabel.text = "\(indexPath.row)" // or where ever you're getting your underlying model data from

init 用于其中任何一项都是一种误解。 init 对表格单元格的唯一职责是分配内存。单元格是一个完全动态的临时对象,其反射(reflect)应用程序数据的所有属性都必须在 cellForRowAtIndexPath 方法中设置。单元格的可视化渲染等待 cellForRowAtIndexPath 方法完成,因此不存在时间问题。

关于ios - 如何将值传递给自定义 UICollectionViewCell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37286414/

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