Reid
Reid

Reputation: 1129

UITextField text stretches when animating width

My app has a text field which shrinks in width when it becomes first responder in order to reveal a "cancel" button, and expands back when the text field resigns first responder. This is all done with autolayout: I have a "trailing space to superview" constraint on the text field. To expand it, I just reduce this constant such that it overlaps the cancel button (whose alpha I fade out at the same time). To collapse it back, I increase the constant again. Pretty standard stuff. The problem is that when the field begins animating, the text distorts in width and then animates back down to its normal proportions as the text field contracts. It's a very weird and undesirable effect. Has anyone experienced this, and do you have any insights on how to prevent it? Thanks!

Screen capture

Upvotes: 2

Views: 456

Answers (2)

Ashley
Ashley

Reputation: 166

I was facing the same problem, and I found this question from a few years ago: Strange behavior when animating UITextField

Its solution worked for me. I was originally trying to animate the width of the UITextField in the following delegate methods:

- (void)textFieldDidBeginEditing:(UITextField *)textField;
- (void)textFieldDidEndEditing:(UITextField *)textField;

This caused the text distortion you are seeing. In order to fix this, I moved the animation to these two delegate methods instead:

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField;
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField;

The text now does not stretch.

Upvotes: 2

JustAnotherCoder
JustAnotherCoder

Reputation: 2575

Perhaps you can try explicitly setting the font size of the UITextField like so:

[textField setFont:[UIFont systemFontOfSize:value]];

and setting adjustsFontSizeToFitWidth to NO or false

textField.adjustsFontSizeToFitWidth = YES;

Upvotes: 0

Related Questions