I am trying to run a function when the keyboard shows and disappears and have the following code:
let notificationCenter = NotificationCenter.default
notific
class ViewController: UIViewController {
@IBOutlet weak var commentsTxt: UITextField!
@IBOutlet weak var keyboardBottom: NSLayoutConstraint!
override func viewWillAppear(_ animated: Bool) {
IQKeyboardManager.shared.enable = false
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboardWillShow),
name: UIResponder.keyboardWillShowNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(keyboarddidHide),
name: UIResponder.keyboardWillHideNotification,
object: nil
)
}
@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
self.keyboardBottom.constant = keyboardHeight - self.bottomLayoutGuide.length
DispatchQueue.main.asyncAfter(deadline: .now()+0.1, execute: {
let bottomOffset = CGPoint(x: 0, y: self.scrlView.contentSize.height - self.scrlView.bounds.size.height)
self.scrlView.setContentOffset(bottomOffset, animated: true)
})
}
}
@objc func keyboarddidHide(_ notification: Notification) {
self.keyboardBottom.constant = 0
}
override func viewWillDisappear(_ animated: Bool) {
IQKeyboardManager.shared.enable = true
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
}
}