Created
November 12, 2015 14:42
-
-
Save KentarouKanno/b546f472d4dab59a05bf to your computer and use it in GitHub Desktop.
AutoLayout + Keyboard ResizeView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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