I am building an app that contains a search or a UITextField and it is located at the bottom of the view near the safe area, so when I touch it and the keyboard pops up, the textfield gets hidden behind the keyboard.
How can I make it so when the keyboard pops up the Textfield moves right above it?
Here is the code I have in the viewController.swift
class ViewController: UIViewController {
@IBOutlet weak var windLabel: UILabel!
@IBOutlet weak var cityLabel: UILabel!
@IBOutlet weak var tempLabel: UILabel!
@IBOutlet weak var searchCItyTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
searchCItyTextField.delegate = self
}
}
//MARK: - UITextFieldDelegate
extension UIViewController: UITextFieldDelegate {
public func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.view.endEditing(true)
return true
}
}
3
Answers
Use the IQKeyboardManager for scroll the UITextField when open the KeyBoard
For Example
In AppDelegate
In ViewController
Output:
You can add an
@IBOutlet
for the bottom constraint of the text field and update this when the keyboard appears/disappears. For example, you set it to-30
from the bottom when there’s no keyboard and update it to-keyboardHeight - 30
if the keyboard is present. See an example of how this can be done here.Another method would be to move the whole view up, for example by using a
UIScrollView
, increasing its height when the keyboard is present and scroll up.You can observe for you keyboard appears or disappears, and updated your interface
For example: