Last active
June 23, 2017 17:00
-
-
Save tsraveling/3437bfa0fb552e22025097f08e19212f to your computer and use it in GitHub Desktop.
Keyboard watchers
This file contains hidden or 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
| var keyboardHeight : CGFloat = 0 | |
| func textFieldDidBeginEditing(_ textField: UITextField) { | |
| let y = textField.frame.origin.y | |
| let h = self.scrollView.frame.size.height | |
| let margin = h - (keyboardHeight + textField.frame.size.height) | |
| self.scrollView.setContentOffset(CGPoint(x: 0, y: y >= margin ? y - margin : 0), animated: true) | |
| } | |
| func keyboardWillShow(notification : NSNotification) { | |
| let info : NSDictionary = notification.userInfo! as NSDictionary; | |
| let frame = info.object(forKey: UIKeyboardFrameEndUserInfoKey) | |
| let key_frame = (frame as AnyObject).cgRectValue | |
| keyboardHeight = (key_frame?.size.height)! | |
| } | |
| func keyboardWillHide(notification : NSNotification) { | |
| self.scrollView.setContentOffset(CGPoint(x: 0, y: 0), animated: true) | |
| } |
This file contains hidden or 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
| func keyboardWillShow(notification : NSNotification) { | |
| let info : NSDictionary = notification.userInfo! as NSDictionary; | |
| let frame = info.object(forKey: UIKeyboardFrameEndUserInfoKey) | |
| let duration = (info.object(forKey: UIKeyboardAnimationDurationUserInfoKey) as AnyObject).doubleValue | |
| let key_frame = (frame as AnyObject).cgRectValue | |
| self.<#T##constraint#>.constant = (key_frame?.size.height)! | |
| UIView.animate(withDuration: duration!) { () -> Void in | |
| self.view.layoutIfNeeded() | |
| } | |
| } | |
| func keyboardWillHide(notification : NSNotification) { | |
| self.<#T##constraint#>.constant = 0 | |
| UIView.animate(withDuration: 0.3) { | |
| self.view.layoutIfNeeded() | |
| } | |
| } |
This file contains hidden or 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
| NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)) , name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil) | |
| NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(notification:)) , name: NSNotification.Name.UIKeyboardWillHide, object: nil) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment