KeyboardAdjuster will adjust the bottom position of any given UIView
when a keyboard appears on screen. All you have to do is provide an NSLayoutConstraint that pins the bottom of your view to the bottom of the screen. KeyboardAdjuster will automatically adjust that constraint and pin it to the top of the keyboard when it appears.
If you're currently choosing between KeyboardAdjuster and another alternative, please read about our philosophy
Note: KeyboardAdjuster requires layout anchors in your build target, so it will only work with iOS 9 or above. If you'd like to add support for earlier iOS versions, please submit a pull request.
KeyboardAdjuster is a Swift port of LHSKeyboardAdjuster, which targets projects written in Objective-C.
KeyboardAdjuster is available through CocoaPods. To install it, simply add the following line to your Podfile:
pod "KeyboardAdjuster"
-
In your view controller file, import
KeyboardAdjuster
.import KeyboardAdjuster
-
Make sure your
UIViewController
conforms toKeyboardAdjuster
, and define two properties. SetkeyboardAdjusterAnimated
totrue
orfalse
, depending on whether you want the constraint adjustment to be animated.class MyViewController: UIViewController, KeyboardAdjuster { var keyboardAdjusterConstraint: NSLayoutConstraint? var keyboardAdjusterAnimated: Bool? = false // ... }
-
Figure out which view you'd like to pin to the top of the keyboard. A
UIScrollView
,UITableView
, orUITextView
are likely candidates. Then, wherever you're setting up your view constraints, setkeyboardAdjusterConstraint
to the constraint pinning the bottom of this view to the bottom of the screen:class MyViewController: UIViewController, KeyboardAdjuster { func viewDidLoad() { super.viewDidLoad() keyboardAdjusterConstraint = view.bottomAnchor.constraintEqualToAnchor(scrollView.bottomAnchor) } }
KeyboardAdjuster will automatically activate
keyboardAdjusterConstraint
for you. -
All you need to do now is activate and deactivate the automatic adjustments in your
viewWillAppear(animated:)
andviewWillDisappear(animated:)
methods.class MyViewController: UIViewController, KeyboardAdjuster { override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) activateKeyboardAdjuster() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) deactivateKeyboardAdjuster() } }
-
And you're done! Whenever a keyboard appears, your views will be automatically resized.
KeyboardAdjuster registers NSNotificationCenter callbacks for keyboard appearance and disappearance. When a keyboard appears, it pulls out the keyboard size from the notification, along with the duration of the keyboard animation, and applies that to the view constraint adjustment.
KeyboardAdjuster is available under the Apache 2.0 LICENSE. See the LICENSE file for more info.