ScrollViews and Keyboards
Adjust the scrolling content of a scrollView when the keyboard is shown and dismissed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
func addKeyboardObservers() { NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil) } deinit { // Cleanup & remove Observers. NotificationCenter.default.removeObserver(self) } func keyboardWillShow(_ notification: Notification) { guard let info = notification.userInfo, let keyboardFrame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return } //Adjust the content inset of the scrollView. let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardFrame.height, right: 0) scrollView.contentInset = insets scrollView.scrollIndicatorInsets = insets // Scroll up to the login button. // Change the loginButton.frame to adjust where the scrollVIew will scroll to. scrollView.scrollRectToVisible(loginButton.frame, animated: true) } func keyboardWillHide(_ notification: Notification) { scrollView.contentInset = UIEdgeInsets.zero } |