如何仅使用 RxSwift + RxCocoa 使用下一步/完成键盘按钮浏览文本字段?
问问题
462 次
1 回答
1
使用简单的 UITextField 扩展,您可以观察文本字段的控制事件并采取相应的行动。
扩大:
import UIKit
import RxSwift
import RxCocoa
extension UITextField {
func resignWhenFinished(_ disposeBag: DisposeBag) {
setNextResponder(nil, disposeBag: disposeBag)
}
func setNextResponder(_ nextResponder: UIResponder?, disposeBag: DisposeBag) {
// Set the return key type to:
// - next: When there is a next responder
// - done: When there is no next responder (simply resign)
returnKeyType = (nextResponder != nil) ? .next : .done
// Subscribe on editing end on exit control event
rx.controlEvent(.editingDidEndOnExit)
.subscribe(onNext: { [weak self, weak nextResponder] in
if let nextResponder = nextResponder {
// Switch to next responder if available
nextResponder.becomeFirstResponder()
} else {
// Otherwise simply resign
self?.resignFirstResponder()
}
})
.addDisposableTo(disposeBag)
}
}
用法:
@IBOutlet private weak var firstTextField: UITextField!
@IBOutlet private weak var secondTextField: UITextField!
@IBOutlet private weak var lastTextField: UITextField!
private let disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
firstTextField.setNextResponder(secondTextField, disposeBag: disposeBag)
secondTextField.setNextResponder(lastTextField, disposeBag: disposeBag)
lastTextField.resignWhenFinished(disposeBag)
}
于 2017-09-08T09:41:14.690 回答