簡體   English   中英

如何將我的 UIButton 標題綁定到我的 ViewModel

[英]How to bind my UIButton title to my ViewModel

我想將UIButton標題綁定到我的 ViewModel 中的BehaviorSubject<String> 我在Label中這樣做,如下所示:

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

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

有什么辦法嗎?

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

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

RxCocoa之后, Reactive還擴展了 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 綁定到按鈕,例如您的示例代碼 label

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

使用 rx swift 的正確方法:

vm.buttonTitle.bind(to: button.rx.title(for: .normal)).disposed(by: bag)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM