'Need to change size of a textField when keyboardWillShow notification is received
I want the text field to do the next when the keyboard appears on the screen:
- Move above the clave
- Stretch to the width of the screen
The first item works, but the second one - doesn't. When opening the application, the text field is attached with snap kit constructs
My code:
@objc private func keyboardWillShow (notification: NSNotification) {
guard let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else { return }
UIView.animate(withDuration: 0.2) {
self.textField.widthAnchor.constraint(equalToConstant: self.view.frame.width).isActive = true
self.textField.frame.origin.y = keyboardSize.origin.y - self.textField.frame.height
}
}
Solution 1:[1]
You cannot change the weight of the text field with rounded corners. Consider to use the UITextView or change text field border style to:
textField.borderStyle = UITextBorderStyleRoundedRect;
UPD: I'm really sorry, I made mistake and read the question incorrectly. In this case, you need to check the logs for autolayout errors. This issue can appear because you have conflicting constraints:
- You have added the width constraint using a storyboard or xib it may conflict with the constraint you are setting in the
keyboardWillShowmethod. - You have added trailing constraint and getting the next conflict. Thus, the trailing constraint trying to make the width smaller than you set to the width constraint:

Solutions:
If you are using storyboard constraints create an outlet of the constraint from the storyboard and change it in the next way:
self.widthConstraint.constant = self.view.frame.width;
Make trailing constraint less than or equal rather than equal. In this way, the width will be changed but the trailing constraint will prevent the text fields to be bigger than the desired paddings. Another way will be to update the trailing constraint instead of the width constraint, but you will need more calculations.
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 |
