This library helps moving your views when a keyboard appears and move them back in place when it hides. It includes helper class for changing the length of a bottom Auto Layout constraint.
There are three ways you can add UnderKeyboard to your project.
Simply add UnderKeyboardDistrib.swift into your project.
Alternatively, add github "evgenyneu/UnderKeyboard" ~> 9.0
to your Cartfile and run carthage update
.
If you are using CocoaPods add this text to your Podfile and run pod install
.
use_frameworks!
target 'Your target name'
pod 'UnderKeyboard', '~> 9.0'
Setup a previous version of the library if you use an older version of Swift.
Add import UnderKeyboard
to your source code if you used Carthage or CocoaPods setup methods.
When a keyboard appears on screen it can obscure your views. One way of preventing it is to create a bottom Auto Layout constraint and increase its length. You can use the UnderKeyboardLayoutConstraint
helper class that does exactly that. Note that bottom layout constraint relation can be a simple equal
or it can be greater than
relation that is used in the login screen of the demo app.
@IBOutlet weak var bottomLayoutConstraint: NSLayoutConstraint!
let underKeyboardLayoutConstraint = UnderKeyboardLayoutConstraint()
override func viewDidLoad() {
super.viewDidLoad()
underKeyboardLayoutConstraint.setup(bottomLayoutConstraint, view: view,
bottomLayoutGuide: bottomLayoutGuide)
}
This library includes the UnderKeyboardObserver
class that you can use to write your own custom logic. You can supply functions that will be called by this observer when the keyboard is shown and hidden. Your function will receive the height of the keyboard. The hight argument is zero if the keyboard is being hidden.
let keyboardObserver = UnderKeyboardObserver()
override func viewDidLoad() {
super.viewDidLoad()
keyboardObserver.start()
// Called before the keyboard is animated
keyboardObserver.willAnimateKeyboard = { height in
myConstraint.constant = height
}
// Called inside the UIView.animateWithDuration animations block
keyboardObserver.animateKeyboard = { height in
myView.layoutIfNeeded()
}
}
Use currentKeyboardHeight
property of the UnderKeyboardObserver
object to get the current keyboard height.
The start
method must first be called to start listening for keyboard notifications. The value returned by currentKeyboardHeight
can be nil
if keyboard state is unknown. It can happen if no keyboard notifications occurred after the start
method was called so we don't know if the keyboard is visible or hidden.
let keyboardObserver = UnderKeyboardObserver()
override func viewDidLoad() {
super.viewDidLoad()
keyboardObserver.start()
}
func myFunction() {
print("Keyboard height: \(keyboardObserver.currentKeyboardHeight)")
}
UnderKeyboard is released under the MIT License.