我正在尝试观察数组变化并将其绑定(bind)到按钮的图像。
如果数组为空。设置空购物车的图片。
否则设置购物车的图像。
所以我所做的是:
let x = itemsArray.observeNext { [weak self] (v) in
let image = v.source.isEmpty ? #imageLiteral(resourceName: "emptyCart") : #imageLiteral(resourceName: "cart")
self?.orderItemsButton.setImage(image, for: .normal)
}
但是如果我确实使用这种方式,我必须在 viewWillDisappear 或类似的东西中处理 x...
正确的做法是什么?
最佳答案
您可以用绑定(bind)替换观察。在这种情况下,一次性由框架本身(ReactiveKit)处理。
您需要做的就是:
itemsArray.bind(to: self) { me, array in
let image = array.source.isEmpty ? #imageLiteral(resourceName: "emptyCart") : #imageLiteral(resourceName: "cart")
me.orderItemsButton.setImage(image, for: .normal)
}
您可以在文档中找到有关绑定(bind)的更多信息: https://github.com/ReactiveKit/ReactiveKit#bindings
我几乎总是建议使用 bind(to:)
而不是 observeNext
。它自动处理weak self
、处置并确保对象在正确的线程上更新。
作为奖励,您还可以通过将数组信号映射到图像信号,然后将其绑定(bind)到按钮来解决此问题(假设您使用的是 ReactiveKit+Bond)。
itemsArray
.map { $0.source.isEmpty ? #imageLiteral(resourceName: "emptyCart") : #imageLiteral(resourceName: "cart") }
.bind(to: orderItemsButton.reactive.image)
关于ios - 如何绑定(bind)数组计数来替换按钮图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48355486/