RxSwift:UIButton

RxSwift在UIButton上应用的

  • observe tap
  • bind btn.title
  • bind btn.image
  • bind isEnable

observe tap

1
2
3
button.rx.tap.subscribe(onNext: { [weak self] in
print("按钮被点击")
}).disposed(by: disposeBag)

bind btn.title

1
2
3
4
5
6
7
//创建一个计时器(每1秒发送一个索引数)
let timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)

//根据索引数拼接最新的标题,并绑定到button上
timer.map{"计数\($0)"}
.bind(to: button.rx.title(for: .normal))
.disposed(by: disposeBag)

bind btn.image

1
2
3
4
5
6
7
8
9
10
//创建一个计时器(每1秒发送一个索引数)
let timer = Observable<Int>.interval(1, scheduler: MainScheduler.instance)

//根据索引数选择对应的按钮图标,并绑定到button上
timer.map({
let name = $0%2 == 0 ? "one" : "two"
return UIImage(named: name)!
})
.bind(to: button.rx.image())
.disposed(by: disposeBag)

bind isEnable

1
2
3
switch1.rx.isOn
.bind(to: button1.rx.isEnabled)
.disposed(by: disposeBag)
  Total:    No.