如何使用Rx浏览UITextFields(Next / Done Buttons)

时间:2017-09-08 09:41:15

标签: uitextfield next rx-swift rx-cocoa

如何使用下一个/完成的键盘按钮浏览文本字段,只使用RxSwift + RxCocoa?

1 个答案:

答案 0 :(得分: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)
}