_ = textField.rx.text.orEmpty.filter({ (text) -> Bool in
text.count > 12
return true
}).subscribe(onNext: { (text) in
let tempText:String = text
self.textField.text = (tempText as NSString).substring(to: 12)
})
它有一些,我需要使用textFieldDidEndEditing
答案 0 :(得分:1)
您可以在RxSwift中使用委托代理模式 首先,我们需要将委托UITextField设置为DelegateProxyType
class RxTextFieldDelegateProxy: DelegateProxy<UITextField, UITextFieldDelegate>, DelegateProxyType, UITextFieldDelegate {
init(textField: UITextField) {
super.init(parentObject: textField, delegateProxy: RxTextFieldDelegateProxy.self)
}
static func registerKnownImplementations() {
self.register { RxTextFieldDelegateProxy(textField: $0)}
}
static func currentDelegate(for object: UITextField) -> UITextFieldDelegate? {
return object.delegate
}
static func setCurrentDelegate(_ delegate: UITextFieldDelegate?, to object: UITextField) {
object.delegate = delegate
}
}
其次,我们可以在RxSwift中自己定义属性。
extension Reactive where Base: UITextField {
public var delegate: DelegateProxy<UITextField, UITextFieldDelegate> {
return RxTextFieldDelegateProxy.proxy(for: base)
}
public var editingDidEnd: Observable<String> {
return delegate.sentMessage(#selector(UITextFieldDelegate.textFieldDidEndEditing(_:))).map { value in
guard let textField = value[0] as? UITextField else { return "" }
return textField.text! }
}
}
第三种用法:
myTextField.rx.editingDidEnd.subscribe(onNext: { value in
debugPrint(value)
}).disposed(by: bag)
答案 1 :(得分:0)
RxSwift 4.0
如果您想使用UITextField
委托方法,则使用`controlEvent。
var bag = DisposeBag()
现在将观察者放在viewDidLoad
方法中。
override func viewDidLoad() {
super.viewDidLoad()
controls.txtTitle.rx
.controlEvent([.editingDidEnd])
.asObservable()
.subscribe(onNext: {
print("Editing done")
}).disposed(by: bag)
}