'How to move UITextFeild with keyboard in order to avoid blocking [SWIFT 5+ ]
I know that there are several questions on this topic, but i have not been able to find any on [SWIFT 5.0] or more, and would really appreciate your help.
I have a UITextFeild at the bottom of the screen which gets hidden every time the user clicks on it. Is there a recent method on which i can solve this hiding issue, by either the textFeild following the keyboard to the top or a sample field appearing on top of the keyboard. Any help would be greatly appreciated, thank you!
Solution 1:[1]
You can use the following code:
First, add these two lines of code in your controller viewDidLoad() method:
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
Second, add these two methods inside your controller:
@objc func keyboardWillShow(notification: NSNotification) {
if yourTextfield.isEditing == true
{
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
self.view.frame.origin.y -= keyboardSize.height
}
}
}
@objc func keyboardWillHide(notification: NSNotification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 64
}
}
Enjoy :).
Solution 2:[2]
If you use AutoLayout you may try Keyboard and KeyboardLayoutGuide from my collection of handy Swift extensions and classes called SwiftToolkit
Add this code to your controller viewDidLoad() method:
let keyboardGuide = KeyboardLayoutGuide()
view.addLayoutGuide(keyboardGuide)
/**
Your textField vertical position constraint
must have lower priority than this constraint
*/
keyboardGuide.topAnchor.constraint(greaterThanOrEqualTo: textField.bottomAnchor, constant: 8).isActive = true
When the keyboard appears it will push your UITextField up like this:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ali Qaderi |
| Solution 2 | Mikhail Vasilev |

