Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Created November 12, 2015 14:42
Show Gist options
  • Save KentarouKanno/b546f472d4dab59a05bf to your computer and use it in GitHub Desktop.
Save KentarouKanno/b546f472d4dab59a05bf to your computer and use it in GitHub Desktop.
AutoLayout + Keyboard ResizeView
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var bottomLayout: NSLayoutConstraint!
let notificationCenter = NSNotificationCenter.defaultCenter()
override func viewDidLoad() {
super.viewDidLoad()
notificationCenter.addObserver(self, selector:"willShowKeyboard:", name: UIKeyboardWillShowNotification, object: nil)
notificationCenter.addObserver(self, selector:"willHideKeyboard:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewDidDisappear(animated: Bool) {
notificationCenter.removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
notificationCenter.removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
func willShowKeyboard(notification: NSNotification) {
let duration = notification.duration()
let keyboardRect = notification.rect()
if let duration = duration, rect = keyboardRect {
self.bottomLayout.constant = rect.size.height - self.bottomLayoutGuide.length;
UIView.animateWithDuration(duration, animations: {
self.view.layoutIfNeeded()
})
}
}
func willHideKeyboard(notification: NSNotification) {
bottomLayout.constant = 0
view.layoutIfNeeded()
}
}
extension NSNotification {
func duration() -> NSTimeInterval? {
let duration: NSTimeInterval? = self.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double
return duration;
}
func rect() -> CGRect? {
let rowRect:NSValue? = self.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue
let rect:CGRect? = rowRect?.CGRectValue()
return rect
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment