gpt4 book ai didi

ios - RxSwift - 无法绑定(bind)自定义 UICollectionViewCell 的变量

转载 作者:搜寻专家 更新时间:2023-11-01 06:30:11 25 4
gpt4 key购买 nike

我有一个自定义的 UICollectionViewCell,里面有一个 UILabel。也有属性 hour,为了示例,它是 String?

我创建了一个名为 bind 的私有(private)函数来配置我的绑定(bind)。这是我的类(class):

class HourCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var hourLabel UILabel!
let hour Variable<String?> = Variable<String?>("")
let disposeBag: DisposeBag = DisposeBag()

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
bind()
}

private func bind() {
hour.asObservable().bind(to: hourLabel.rx.text).disposed(by: disposeBag)
hour.asObservable().subscribe(onNext: {debugPrint("New hour: \($0 ?? "--")")}).disposed(by: disposeBag)
}
}

在所需的 init 中调用 bind 可能会出现问题。有时 hourLabel 仍未初始化。此外,在 init(frame: CGRect) 中调用此函数永远不会触发 bind 函数,这很尴尬。我以为这个函数总是被调用。

尽管这是一个简单的绑定(bind),但我无法正确实现它。

在我的 UICollectionViewController 中,我有这个函数来填充自定义单元格中的 hour 属性:

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HourCollectionViewCell", for: indexPath) as! HourCollectionViewCell
var text: String = "\(indexPath.row)"

// This does not work because `bind` method
// is never called.
cell.hour.value = text

return cell
}

更新:我已经看到当我从 Storyboard 初始化 View 时调用了 init:coder,就是这种情况。

我见过的解决方法 here是从 layoutSubviews 内部调用 bind。这样一切都有效。这是更好的方法吗?

最佳答案

你的电池是可重复使用的,所以你应该清理垃圾袋。

class HourCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var hourLabel UILabel!
let hour = PublishRelay<String?>()
private(set) var disposeBag = DisposeBag()

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}

func bind() {
hour.asDriver(onErrorJustReturn: "").debug().drive( hourLabel.rx.text).disposed(by: disposeBag)
}

override prepareForReuse() {
super.prepareForReuse()
disposeBag = DisposeBag()
}
}

我使用了 PublishRelay 作为 Variable 已弃用,并将其设为 Driver 以确保我们在 mainThread 上。您可以使用 debug() 在控制台中打印事件。

因为在重用时我们清除了 disposeBag,我们可以从 UICollectionViewController 中调用绑定(bind):

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HourCollectionViewCell", for: indexPath) as! HourCollectionViewCell
var text: String = "\(indexPath.row)"

cell.bind()
cell.hour.accept(text)

return cell
}

我鼓励您查看 RxDataSources,因为 UICollectionViewController 为每个单元格提供一个模型可能更好。

关于ios - RxSwift - 无法绑定(bind)自定义 UICollectionViewCell 的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505049/

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