ios - 如何绑定(bind)数组计数来替换按钮图像

标签 ios swift rx-swift reactivekit

我正在尝试观察数组变化并将其绑定(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/

相关文章:

ios - tableView 更新期间对数据源的线程安全访问

ios - Realm 过滤器结果使用哪种类型

ios - 在 RxSwift 中观察其他 ViewController 中的对象变化

ios - 来自 CloudKit 的推送通知未正确同步

ios - 如何在 Swift 中使用 UITextField 从图像中提取特定文本?

ios - 如果它在 TabBarController 中,如何从 AppDelegate 访问 ViewController 的属性?

swift - FlatMapLatest 跳过触发,直到最新的可观察完成

ios - RxSwift : Combine two network request to return one value

iphone - 是否可以保留“应用程序报告”用户位置?

ios - PDFAnnotationSubtype 等于 .widget 的 PDFAnnotation 在将其添加到 PDFPage 后不会刷新其外观