【问题标题】:How to bind my UIButton title to my ViewModel如何将我的 UIButton 标题绑定到我的 ViewModel
【发布时间】:2020-03-06 07:24:24
【问题描述】:

我想在我的 ViewModel 中将 UIButton 标题绑定到 BehaviorSubject<String>。我在Label 中进行操作,如下所示:

//ViewModel
var fullName = BehaviorSubject<String?>(value: "")

//ViewController
vm.fullName.bind(to: fullNameLabel.rx.text).disposed(by: bag)

有什么办法吗?

【问题讨论】:

    标签: ios swift mvvm rx-swift


    【解决方案1】:

    正确的方法是使用title() binder。

    vm.fullName
        .bind(to: button.rx.title())
        .disposed(by: disposeBag)
    

    【讨论】:

      【解决方案2】:

      RxCocoaReactive 之后也可以扩展 UIButton titleattributedTitle 来绑定它

      请查看此 [RxSwift/UIButton+Rx.swift] 链接 (https://github.com/ReactiveX/RxSwift/blob/master/RxCocoa/iOS/UIButton%2BRx.swift)

      extension Reactive where Base: UIButton {
      
          /// Reactive wrapper for `setTitle(_:for:)`
          public func title(for controlState: UIControl.State = []) -> Binder<String?> {
              return Binder(self.base) { button, title -> Void in
                  button.setTitle(title, for: controlState)
              }
          }
      }
      
      extension Reactive where Base: UIButton {
      
          /// Reactive wrapper for `setAttributedTitle(_:controlState:)`
          public func attributedTitle(for controlState: UIControl.State = []) -> Binder<NSAttributedString?> {
              return Binder(self.base) { button, attributedTitle -> Void in
                  button.setAttributedTitle(attributedTitle, for: controlState)
              }
          }
      
      }
      

      因此您可以将您的全名 BehaviorSubject 绑定到按钮,例如您的示例代码标签

      vm.fullName.bind(to: someButton.rx.title()).disposed(by: bag)
      

      【讨论】:

      • 在“Reactive”上引用实例方法“title(for:)”要求“String._ObjectiveCType”(又名“NSString”)继承自“UIButton”
      猜你喜欢
      • 2016-11-17
      • 1970-01-01
      • 2011-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多