Last active
August 23, 2021 02:32
-
-
Save wassim93/07dda005cf7a0c24323fa759bcf3ce2e to your computer and use it in GitHub Desktop.
keyboard handling swift
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) { | |
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardDidShow(notification:)), | |
name: UIResponder.keyboardDidShowNotification, object: nil) | |
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardWillBeHidden(notification:)), | |
name: UIResponder.keyboardWillHideNotification, object: nil) | |
} | |
override func viewWillDisappear(_ animated: Bool) { | |
NotificationCenter.default.removeObserver(self) | |
} | |
// MARK: - keyboard handling functions | |
@objc func keyboardDidShow(notification: NSNotification) { | |
let userInfo = notification.userInfo! | |
var keyboardFrame:CGRect = (userInfo[UIResponder.keyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue | |
keyboardFrame = self.view.convert(keyboardFrame, from: nil) | |
var contentInset:UIEdgeInsets = self.scrollView.contentInset | |
contentInset.bottom = keyboardFrame.size.height + 5 | |
scrollView.contentInset = contentInset | |
} | |
@objc func keyboardWillBeHidden(notification: NSNotification) { | |
let contentInsets = UIEdgeInsets.zero | |
self.scrollView.contentInset = contentInsets | |
self.scrollView.scrollIndicatorInsets = contentInsets | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment