Skip to content

Instantly share code, notes, and snippets.

@erikfloresq
Last active March 8, 2016 04:23
Show Gist options
  • Save erikfloresq/1c0eff3b25f897b786a3 to your computer and use it in GitHub Desktop.
Save erikfloresq/1c0eff3b25f897b786a3 to your computer and use it in GitHub Desktop.
Show keyboard with scrollview
// properti
var tapper:UIGestureRecognizer!
// hide keyboard with tap
self.tapper = UITapGestureRecognizer(target: self, action: "handleSingleTapToHideKeyboard:")
self.view.addGestureRecognizer(self.tapper)
func handleSingleTapToHideKeyboard(sender:UITapGestureRecognizer) {
self.view.endEditing(true)
}
// MARK:- Keyboard
override func viewWillAppear(animated: Bool) {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillDisappear(animated: Bool) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}
func keyboardWillShow(notification: NSNotification) {
let userInfo: NSDictionary = notification.userInfo!
let keyboardSize = userInfo.objectForKey(UIKeyboardFrameBeginUserInfoKey)!.CGRectValue.size
let contentInsets = UIEdgeInsetsMake(0, 0, keyboardSize.height-30, 0)
self.scrollView.contentInset = contentInsets
self.scrollView.scrollIndicatorInsets = contentInsets
var viewRect = view.frame
viewRect.size.height -= keyboardSize.height
if CGRectContainsPoint(viewRect, self.userDniView.frame.origin) {
let scrollPoint = CGPointMake(0, self.userDniView.frame.origin.y - keyboardSize.height)
self.scrollView.setContentOffset(scrollPoint, animated: true)
}
}
func keyboardWillHide(notification: NSNotification) {
self.scrollView.contentInset = UIEdgeInsetsZero
self.scrollView.scrollIndicatorInsets = UIEdgeInsetsZero
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment