I'm experiencing a glitch where my UITextField's text jumps to its final position (it doesn't animate) when animating the textfield's width constraint. Take a look at this gif:
When the "Grow" button is tapped, the textfield's width grows. But "hello world" jumps immediately to the center instead of gliding there. When the "Shrink" button is tapped, "hello world" jumps immediately back to the left.
My animation function looks like this:
func animateGrowShrinkTextFields(grow: Bool) {
if grow {
UIView.animate(withDuration: 0.5, animations: {
self.widthConstraint.constant = 330
self.view.layoutIfNeeded()
}, completion: nil)
} else {
UIView.animate(withDuration: 0.5, animations: {
self.widthConstraint.constant = 100
self.view.layoutIfNeeded()
}, completion: nil)
}
}
I have tried the following list suggestions; none of them worked.
- I called
self.view.layoutIfNeeded()
andself.helloWorldTextField.layoutIfNeeded()
before and within the animation block as suggested in this answer: https://stackoverflow.com/a/32996503/2179970 - I tried
self.view.layoutSubviews
andself.helloWorldTextField.layoutSubview
as suggested in this answer: https://stackoverflow.com/a/30845306/2179970 - Also tried
setNeedsLayout()
UITextField text jumps iOS 9 - I even tried changing the font as suggested here: https://stackoverflow.com/a/35681037/2179970
- I tried
resignFirstResponder
(although though I never tap or edit the textfield in my tests, so it should not involve the firstResponder) as suggested here: https://stackoverflow.com/a/33334567/2179970 - I tried subclassing UITextField as seen here: https://stackoverflow.com/a/40279630/2179970
- I also tried using a UILabel and got the same jumpy result.
The following question is also very similar to mine but does not have an answer yet: UITextfield text position not animating while width constraint is animated
Here is my project on Github: https://github.com/starkindustries/ConstraintAnimationTest