RxSwift应用 UITextField相关

简单记录下RxSwift在UITextField中的常用操作

  • 监听输入+节流
  • 绑定输入到其它对象
  • 输入监听判断
  • 同时监听多个输入
  • 监听controlEvent变化

初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import UIKit
import RxSwift
import RxCocoa
public class JDBaseViewController: UIViewController {
let disposeBag = DisposeBag()
@IBOutlet weak var textField: UITextField!

@IBOutlet weak var textField2: UITextField!

@IBOutlet weak var label: UILabel!
@IBOutlet weak var btn: UIButton!

override public func viewDidLoad() {
super.viewDidLoad()

}

/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}

监听输入+节流

1
let input = self.textField.rx.text.orEmpty.asDriver().throttle(0.3)

绑定输入到其它对象

1
input.drive(self.textField2.rx.text).disposed(by: self.disposeBag)

输入监听判断

1
input.map{ $0.count > 5 }.drive(self.btn.rx.isEnabled).disposed(by: self.disposeBag)

同时监听多个输入

1
2
3
4
5
6
7
Observable.combineLatest(self.textField01.rx.text.orEmpty, self.textField02.rx.text.orEmpty) {
textValue1, textValue2 -> String in
return "input is: \(textValue1) -- \(textValue2)"
}
.map{$0}
.bind(to: self.label.rx.text)
.disposed(by: self.disposeBag)

监听controlEvent变化

1
2
3
4
5
self.textField02.rx.controlEvent([UIControlEvents.editingDidBegin])
.asObservable()
.subscribe(onNext: { _ in
print("begin edit")
}).disposed(by: self.disposeBag)
  Total:    No.