RxSwift(五) - Observer(自定义可绑定属性)

一、自定义可绑定属性

UI控件添加一些默认观察者,比如添加 fontSize 可绑定属性:

方式一: 通过对 UI 类进行扩展

UILabel 进行扩展, 增加一个 fontSize 可绑定属性

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var button: UIButton!
    let disposeBag = DisposeBag()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let observable = Observable.interval(1, scheduler: MainScheduler.instance)
        observable.map {CGFloat($0)}
            .bind(to: label.fontSize)
        .disposed(by: disposeBag)
        
    }
}

extension UILabel {
    public var fontSize: Binder {
        return Binder(self) { label, fontSize in
            label.font = UIFont.systemFont(ofSize: fontSize)
        }
    }
}
方式二: 对 Reactive 类进行扩展

更规范的写法是应该对 Reactive 进行扩展, 同样给出上面示例 :

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var button: UIButton!
    let disposeBag = DisposeBag()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let observable = Observable.interval(1, scheduler: MainScheduler.instance)
        observable.map {CGFloat($0)}
            .bind(to: label.rx.fontSize)
        .disposed(by: disposeBag)
        
    }
}

extension Reactive where Base: UILabel {
    public var fontSize: Binder {
        return Binder(self.base) {label, fontSize in
            label.font = UIFont.systemFont(ofSize: fontSize)
        }
    }
}

RxCocoa 自带的可绑定属性

(1) RxCocoa 已经提供了许多常用可绑定属性, 比如 UILabel 就有 textattributedText 两个可绑定属性

extension Reactive where Base: UILabel {
    
    /// Bindable sink for `text` property.
    public var text: Binder {
        return Binder(self.base) { label, text in
            label.text = text
        }
    }

    /// Bindable sink for `attributedText` property.
    public var attributedText: Binder {
        return Binder(self.base) { label, text in
            label.attributedText = text
        }
    }
    
}

(2) 显示索引数的案例 :

class ViewController: UIViewController {

    @IBOutlet weak var label: UILabel!
    @IBOutlet weak var button: UIButton!
    let disposeBag = DisposeBag()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let observable = Observable.interval(1, scheduler: MainScheduler.instance)
        observable.map {"当前索引数 \($0)"}
            .bind(to: label.rx.text)
        .disposed(by: disposeBag)
        
    }
}

你可能感兴趣的:(RxSwift(五) - Observer(自定义可绑定属性))