Skip to content

Instantly share code, notes, and snippets.

@pangers
Last active December 28, 2016 08:24
Show Gist options
  • Save pangers/399ed3f4c6b57d6db5dc4b108e5984e9 to your computer and use it in GitHub Desktop.
Save pangers/399ed3f4c6b57d6db5dc4b108e5984e9 to your computer and use it in GitHub Desktop.
//MARK: - Private
fileprivate extension KeyboardAvoidable where Self: UIViewController {
func keyboardWillAppear(_ notification: Notification) {
//1
let keyboardInfo = KeyboardNotification(notification)
let duration = keyboardInfo.animationDuration
let curve = keyboardInfo.animationCurve
let keyboardEndFrame = keyboardInfo.keyboardFrameEnd
//This check needs to be done because keyboardWillAppear could get called twice in a row
//Eg. If you focus on a UITextField, then focus on another UITextField without dismissing the Keyboard
//We only need to adjust the view frame on the first time
//2
if !keyboardOpen && !keyboardInfo.keyboardHeightChanged {
//This means the keyboard is appearing from disappeared state
view.frame.size.height -= keyboardEndFrame.height
animate(with: duration, and: curve, keyboardOpened: true)
//3
} else if keyboardOpen && keyboardInfo.keyboardHeightChanged {
//This means something about the keyboard change
//Eg. Word suggestions hidden/show
view.frame.size.height += -keyboardInfo.keyboardHeightDelta
animate(with: duration, and: curve, keyboardOpened: true)
}
}
func keyboardWillDisappear(_ notification: Notification) {
//1
let keyboardInfo = KeyboardNotification(notification)
let duration = keyboardInfo.animationDuration
let curve = keyboardInfo.animationCurve
let keyboardStartFrame = keyboardInfo.keyboardFrameStart
//2
if keyboardOpen {
view.frame.size.height += keyboardStartFrame.height
animate(with: duration, and: curve, keyboardOpened: false)
}
}
func animate(with duration: TimeInterval, and options: UIViewAnimationOptions, keyboardOpened: Bool) {
UIView.animate(withDuration: duration,
delay: 0,
options: options,
animations: { self.view.layoutIfNeeded() },
completion: {
completed in
self.keyboardOpen = keyboardOpened
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment