Skip to content

Instantly share code, notes, and snippets.

@CassiusPacheco
Created December 14, 2017 03:25
Show Gist options
  • Select an option

  • Save CassiusPacheco/3e17c15693a12c440f7f2191428fb834 to your computer and use it in GitHub Desktop.

Select an option

Save CassiusPacheco/3e17c15693a12c440f7f2191428fb834 to your computer and use it in GitHub Desktop.
View Resizer when Keyboard Appears
// MARK: - View Resizer when Keyboard Appears
extension UIViewController {
// This implementation was taken from: https://newfivefour.com/swift-ios-xcode-resizing-on-keyboard.html
// to improve the user experience the view updates will happen with the same animation as the keyboard's
func setupViewResizerOnKeyboardShown() {
NotificationCenter.default.addObserver(self,
selector: #selector(UIViewController.keyboardWillShowForResizing),
name: Notification.Name.UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(UIViewController.keyboardWillHideForResizing),
name: Notification.Name.UIKeyboardWillHide,
object: nil)
}
@objc
func keyboardWillHideForResizing(notification: Notification) {
self.extractKeyboardUserInfo(notification.userInfo) { (keyboardSize) in
let viewHeight = self.view.frame.height
self.view.frame = CGRect(x: self.view.frame.origin.x,
y: self.view.frame.origin.y,
width: self.view.frame.width,
height: viewHeight + keyboardSize.height)
}
}
@objc
func keyboardWillShowForResizing(notification: Notification) {
// We're not just minusing the kb height from the view height because
// the view could already have been resized for the keyboard before
self.extractKeyboardUserInfo(notification.userInfo) { (keyboardSize) in
guard let window = self.view.window?.frame else { return }
self.view.frame = CGRect(x: self.view.frame.origin.x,
y: self.view.frame.origin.y,
width: self.view.frame.width,
height: window.origin.y + window.height - keyboardSize.height)
}
}
private func extractKeyboardUserInfo(_ userInfo: [AnyHashable: Any]?, andPerform animation: @escaping (CGRect) -> Void) {
if let keyboardSize = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
// extract animation duration and animation curve from the notification, so the UIView update occurs during the keyboard animation
if let animationDuration = (userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,
let curveInteger = (userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue {
let animationCurve = UIViewAnimationOptions(rawValue: curveInteger)
UIView.animate(withDuration: animationDuration, delay: 0.0, options: animationCurve, animations: {
animation(keyboardSize)
}, completion: nil)
}
else {
// for some weird reason we couldn't get the animation info, so just update the UIView with no animation
animation(keyboardSize)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment