RxSwift 的双向绑定 给UILabel 添加 ControlProperty 属性

在使用RxSwift的时候,ViewMode 与View之间的绑定事件,我们都知道,许多 UI 控件(switch, datePicker, textView, textField)既是可被监听的序列也是观察者,这种特性,我们只需要在View里面绑定一下,ViewModel 即可接收到View值的变化

        self.userViewModel = viewModel
        //初始化input
//        viewModel.loginViewType = self.loginViewType
        viewModel.usernameObservable = accountTextField.rx.text.orEmpty.asObservable()
        viewModel.passwordObservable = passwordTextField.rx.text.orEmpty.asObservable()
        
        //bind data
        accountTextField.rx.text.orEmpty.bind(to: viewModel.username).disposed(by: disposeBag)
        passwordTextField.rx.text.orEmpty.bind(to: viewModel.password).disposed(by: disposeBag)

可是UILable 却不能,通过查看文档,发现

public struct ControlProperty : ControlPropertyType {
    public typealias E = PropertyType

    let _values: Observable
    let _valueSink: AnyObserver

    /// Initializes control property with a observable sequence that represents property values and observer that enables
    /// binding values to property.
    ///
    /// - parameter values: Observable sequence that represents property values.
    /// - parameter valueSink: Observer that enables binding values to control property.
    /// - returns: Control property created with a observable sequence of values and an observer that enables binding values
    /// to property.
    public init(values: V, valueSink: S) where E == V.E, E == S.E {
        self._values = values.subscribeOn(ConcurrentMainScheduler.instance)
        self._valueSink = valueSink.asObserver()
    }

    /// Subscribes an observer to control property values.
    ///
    /// - parameter observer: Observer to subscribe to property values.
    /// - returns: Disposable object that can be used to unsubscribe the observer from receiving control property values.
    public func subscribe(_ observer: O) -> Disposable where O.E == E {
        return self._values.subscribe(observer)
    }

他们都遵循了ControlPropertyType这个属性,如果我们给UILable添加这个属性,这就大大方便了我们绑定事件。

import UIKit

extension UILabel{
    
    
    public var rx_text: ControlProperty {
        // 观察text
        let source: Observable = self.rx.observe(String.self, "text").map { $0 ?? "" }
        let setter: (UILabel, String) -> Void = { $0.text = $1 }
        let bindingObserver = UIBindingObserver(UIElement: self, binding: setter)
        return ControlProperty(values: source, valueSink: bindingObserver)
    }

    
}

这样我们就可以这样写了,简单暴力

        allBookingTitleLabel.rx_text.bind(to: viewModel.markStatus).disposed(by: disposeBag)
        allLocationTitleLabel.rx_text.bind(to: viewModel.city).disposed(by: disposeBag)
        startTimeLabel.rx_text.bind(to: viewModel.starttime).disposed(by: disposeBag)
        endTimeLabel.rx_text.bind(to: viewModel.endtime).disposed(by: disposeBag)

你可能感兴趣的:(Swift,Rxswift,开发)