简体   繁体   中英

Use RxSwift to handle the keyboardWillHide

I would like to enable a button when the keyboard is hidden. How can I do this using rxSwift? I tried this code but the closure is never called:

NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification)
    .map { _ in if let cancelButton = self.searchBar.value(forKey: "cancelButton") as? UIButton {
    cancelButton.isEnabled = true
} }

Observables don't do anything unless they are subscribed to. Since you did not use a subscribe (or bind which is a subscribe that asserts if an error is observed) the Observer didn't do anything. It's kind of like creating an object but never calling any of its functions.

I would write it like this:

let cancelButton = searchBar.value(forKey: "cancelButton") as! UIButton
NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification)
    .map { _ in true }
    .take(1)
    .subscribe(cancelButton.rx.isEnabled)
    .disposed(by: disposeBag)

Daniel's answer is correct and probably the simplest way of doing it, but here is another example of doing the same thing using RxCocoa:

let keyboardShown = NotificationCenter.default.rx.notification(UIResponder.keyboardWillShowNotification)
let keyboardHidden = NotificationCenter.default.rx.notification(UIResponder.keyboardWillHideNotification)

let isCancelEnabled = Observable.merge(keyboardShown.map { _ in false }, keyboardHidden.map { _ in true })
    .startWith(false)
    .asDriver(onErrorJustReturn: false)

let cancelButton = searchBar.value(forKey: "cancelButton") as! UIButton

isCancelEnabled
    .drive(cancelButton.rx.isEnabled)
    .disposed(by: disposeBag)

This might be a slightly longer version of doing it but it is now very simple to employ an MVVM pattern, with the isCancelEnabled being declared in the ViewModel and cancelButton 'driving' in the ViewController.

PS I don't think you want to include the.take(1) as suggested by Daniel as this will work fine for the first event but then the subscription will get disposed and it will no longer work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM