gpt4 book ai didi

swift - 使用 RxSwift 处理 keyboardWillHide

转载 作者:行者123 更新时间:2023-12-04 11:01:51 25 4
gpt4 key购买 nike

我想在键盘隐藏时启用一个按钮。我如何使用 rxSwift 做到这一点?我试过这段代码,但从未调用过闭包:

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

最佳答案

Daniel 的回答是正确的,可能是最简单的方法,但这里是另一个使用 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)

这可能是一个稍长的版本,但现在使用 MVVM 模式非常简单,在 ViewModel 中声明 isCancelEnabled,在 ViewController 中声明 cancelButton 'driving'。

附言我认为您不希望按照 Daniel 的建议包含 .take(1) ,因为这对于第一个事件可以正常工作,但随后订阅将被处理,它将不再起作用。

关于swift - 使用 RxSwift 处理 keyboardWillHide,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58758524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com