Last active
March 8, 2022 09:15
-
-
Save KrauserHuang/2d744dfd0330d8ce447024f8a4f04383 to your computer and use it in GitHub Desktop.
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 registerForKeyboardNotifications() { | |
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(_:)), name: UIResponder.keyboardWillShowNotification, object: nil) | |
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(_:)), name: UIResponder.keyboardWillHideNotification, object: nil) | |
} | |
@objc func keyboardWasShown(_ notification: Notification) { | |
guard let info = notification.userInfo, | |
let keyboardFrameValue = info[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return } | |
let keyboardFrame = keyboardFrameValue.cgRectValue | |
let keyboardSize = keyboardFrame.size | |
// set contentInset to add it on scrollView and match with keyboard height | |
// contentInset is an additional blank space you can use since keyboard is overlap on you view, you create contentInset to avoid overlapping | |
let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0) | |
scrollView.contentInset = contentInsets | |
scrollView.scrollIndicatorInsets = contentInsets | |
} | |
@objc func keyboardWillBeHidden(_ notification: Notification) { | |
let contentInsets = UIEdgeInsets.zero | |
scrollView.contentInset = contentInsets | |
scrollView.scrollIndicatorInsets = contentInsets | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment