Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hlung/532382d5cc52b0283d9a9c1445f08382 to your computer and use it in GitHub Desktop.
Save hlung/532382d5cc52b0283d9a9c1445f08382 to your computer and use it in GitHub Desktop.
RxSwift Observable on iOS keyboard height. Updated from original. Changelog below.
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())
}
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") }
}
@hlung
Copy link
Author

hlung commented May 8, 2018

Update from original:

  • Change to return Driver instead.
  • Refactor keyboard height parsing and add animation duration.
  • Use UIKeyboardFrameEndUserInfoKey instead of UIKeyboardFrameBeginUserInfoKey.
  • Update usage example with change animation.

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