Last active
March 8, 2016 15:14
-
-
Save johanhar/c405a6d7bcd9ba8626a8 to your computer and use it in GitHub Desktop.
iOS keyboard scrollview tableview
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
override func viewWillAppear(animated: Bool) { | |
super.viewWillAppear(animated) | |
registerKeyboardNotifications() | |
} | |
override func viewWillDisappear(animated: Bool) { | |
super.viewWillDisappear(animated) | |
unregisterKeyboardNotifications() | |
} | |
func registerKeyboardNotifications() { | |
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow:", name: UIKeyboardDidShowNotification, object: nil) | |
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil) | |
} | |
func unregisterKeyboardNotifications() { | |
NSNotificationCenter.defaultCenter().removeObserver(self) | |
} | |
func keyboardDidShow(notification: NSNotification) { | |
let userInfo: NSDictionary = notification.userInfo! | |
let keyboardSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size | |
let contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height, 0) | |
scrollView.contentInset = contentInsets | |
scrollView.scrollIndicatorInsets = contentInsets | |
var viewRect = view.frame | |
viewRect.size.height -= keyboardSize.height | |
if CGRectContainsPoint(viewRect, question.frame.origin) { | |
let scrollPoint = CGPointMake(0, question.frame.origin.y - keyboardSize.height) | |
scrollView.setContentOffset(scrollPoint, animated: true) | |
} | |
} | |
func keyboardWillHide(notification: NSNotification) { | |
scrollView.contentInset = UIEdgeInsetsZero | |
scrollView.scrollIndicatorInsets = UIEdgeInsetsZero | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment