Forked from laurilehmijoki/keyboardHeightObservable.swift
Last active
June 11, 2023 11:41
-
-
Save hlung/532382d5cc52b0283d9a9c1445f08382 to your computer and use it in GitHub Desktop.
RxSwift Observable on iOS keyboard height. Updated from original. Changelog below.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import RxSwift // Version 3.2.0 | |
import RxCocoa // Version 3.2.0 | |
typealias KeyboardHeightInfo = (CGFloat, TimeInterval) | |
func keyboardHeight() -> Driver<KeyboardHeightInfo> { | |
return Observable | |
.from([ | |
NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillShow) | |
.map { notification -> KeyboardHeightInfo in | |
let userInfo = notification.userInfo | |
let value = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue.height ?? 0 | |
let animationDuration = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0 | |
return (value, animationDuration) | |
}, | |
NotificationCenter.default.rx.notification(NSNotification.Name.UIKeyboardWillHide) | |
.map { notification -> KeyboardHeightInfo in | |
let userInfo = notification.userInfo | |
let animationDuration = userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval ?? 0 | |
return (0, animationDuration) | |
} | |
]) | |
.merge() | |
.asDriver(onErrorDriveWith: Driver.never()) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import RxSwift // Version 3.2.0 | |
import RxCocoa // Version 3.2.0 | |
import UIKit | |
class MyView: UIView { | |
fileprivate disposeBag = DisposeBag() | |
// Note: tableView and constraints are omitted here. | |
private lazy var resultTableViewBottomConstraint: NSLayoutConstraint = { | |
return NSLayoutConstraint(item: view, attribute: .bottom, relatedBy: .equal, | |
toItem: tableView, attribute: .bottom, multiplier: 1.0, constant: 0) | |
}() | |
init() { | |
super.init(frame: CGRect.zero) | |
keyboardHeight() | |
.drive(onNext: { [unowned self] (value, animationDuration) in | |
self.resultTableViewBottomConstraint.constant = value | |
UIView.animate(withDuration: animationDuration, animations: { () -> Void in | |
self.view.layoutIfNeeded() | |
}) | |
}) | |
} | |
required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Update from original:
Driver
instead.UIKeyboardFrameEndUserInfoKey
instead ofUIKeyboardFrameBeginUserInfoKey
.