I want to move textfield up when keyword covers the textfield. Now I am facing a problem with the moving textfield up: it moves up but every time when I click one of the textfields.
How to move the textfield up only when it is covered by keyword?
Also, I have scrolling when the textfield tapped, but it does not work correctly
Here is my code:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
self.hideKeyboardWhenTappedAround()
}
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
if view.frame.origin.y == 0 {
self.view.frame.origin.y -= keyboardSize.height
}
}
guard let userInfo = notification.userInfo else { return }
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 + 20
scrollView.contentInset = contentInset
}
@objc func keyboardWillHide(notification: NSNotification) {
let contentInset:UIEdgeInsets = UIEdgeInsets.zero
scrollView.contentInset = contentInset
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
2
Answers
Simply use this cocoapods to manage all text fields
Here is a reference link — IQKeyboardManagerSwift
Solutions.
First way you can listen
keyboardWillChangeFrameNotification
Second way you can hide keywords
textField.autocorrectionType = .no