Reactive Keyboard in iOS
RxKeyboard provides a reactive way of observing keyboard frame changes. Forget about keyboard notifications. It also perfectly works with UIScrollViewKeyboardDismissMode.interactive
.
RxKeyboard provides two Driver
s.
/// An observable keyboard frame.
let frame: Driver<CGRect>
/// An observable visible height of keyboard. Emits keyboard height if the keyboard is visible
/// or `0` if the keyboard is not visible.
let visibleHeight: Driver<CGFloat>
/// Same with `visibleHeight` but only emits values when keyboard is about to show. This is
/// useful when adjusting scroll view content offset.
let willShowVisibleHeight: Driver<CGFloat>
Use RxKeyboard.instance
to get singleton instance.
RxKeyboard.instance
Subscribe RxKeyboard.instance.frame
to observe keyboard frame changes.
RxKeyboard.instance.frame
.drive(onNext: { frame in
print(frame)
})
.disposed(by: disposeBag)
đź”— I want to adjust UIScrollView
’s contentInset
to fit keyboard height.
RxKeyboard.instance.visibleHeight
.drive(onNext: { [scrollView] keyboardVisibleHeight in
scrollView.contentInset.bottom = keyboardVisibleHeight
})
.disposed(by: disposeBag)
đź”— I want to adjust UIScrollView
’s contentOffset
to fit keyboard height.
RxKeyboard.instance.willShowVisibleHeight
.drive(onNext: { [scrollView] keyboardVisibleHeight in
scrollView.contentOffset.y += keyboardVisibleHeight
})
.disposed(by: disposeBag)
đź”— I want to make UIToolbar
move along with the keyboard in an interactive dismiss mode. (Just like the wonderful GIF above!)
If you’re not using Auto Layout:
RxKeyboard.instance.visibleHeight
.drive(onNext: { [toolbar, view] keyboardVisibleHeight in
toolbar.frame.origin.y = view.frame.height - toolbar.frame.height - keyboardVisibleHeight
})
.disposed(by: disposeBag)
If you’re using Auto Layout, you have to capture the toolbar’s bottom constraint and set constant
to keyboard visible height.
RxKeyboard.instance.visibleHeight
.drive(onNext: { [toolbarBottomConstraint] keyboardVisibleHeight in
toolbarBottomConstraint.constant = -1 * keyboardVisibleHeight
})
.disposed(by: disposeBag)
Note: In real world, you should use
setNeedsLayout()
andlayoutIfNeeded()
with animation block. See the example project for example.
Anything else? Please open an issue or make a Pull Request.
In development, RxKeyboard manages dependencies with Swift Package Manager. Use the command below in order to generate a Xcode project file. Note that .xcodeproj
file changes are not tracked via git.
$ swift package generate-xcodeproj
Using CocoaPods:
pod 'RxKeyboard'
Using Carthage:
binary "https://raw.githubusercontent.com/RxSwiftCommunity/RxKeyboard/master/RxKeyboard.json"
⚠️ With Carthage, RxKeyboard only supports binary installation:
RxKeyboard is under MIT license.