Skip to content

Instantly share code, notes, and snippets.

@laurilehmijoki
Last active November 15, 2022 13:00
Show Gist options
  • Star 42 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save laurilehmijoki/193332408964ad53e1cc236387ec6e46 to your computer and use it in GitHub Desktop.
Save laurilehmijoki/193332408964ad53e1cc236387ec6e46 to your computer and use it in GitHub Desktop.
RxSwift Observable on iOS keyboard height
import RxSwift // Version 3.2.0
import RxCocoa // Version 3.2.0
func keyboardHeight() -> Observable<CGFloat> {
return Observable
.from([
NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillShow)
.map { notification -> CGFloat in
(notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.height ?? 0
},
NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillHide)
.map { _ -> CGFloat in
0
}
])
.merge()
}
import RxSwift // Version 3.2.0
import RxCocoa // Version 3.2.0
import UIKit
class MyView: UIView {
fileprivate disposeBag = DisposeBag()
init() {
super.init(frame: CGRect.zero)
keyboardHeight()
.observeOn(MainScheduler.instance)
.subscribe(onNext: { (keyboardHeight): CGFloat in
// adjust other views with keyboardHeight
})
.addDisposableTo(disposeBag)
}
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") }
}
@EliaECoyote
Copy link

This worked well for me, but I had to replace UIKeyboardFrameBeginUserInfoKey with UIKeyboardFrameEndUserInfoKey to get the correct height value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment