Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField text vertically shifts after Dynamic Type Resize

I am using Dynamic Type in my app. If I start it with Dynamic Type in the smallest text size mode, and click on the UITextField to edit, everything is fine. It opens the keyboard, and the text stays still.

Then when I go out, change the text size to the largest text size mode, and switch back, it will resize the text in the textfield, as it should.

However, when I click on the UITextField to edit, the text inside it vertically shifts each time.

Below is a GIF of when I just came back from changing the size setting (notice how "Sample Text" shifts vertically):

Sample Text shifts vertically in UITextField

This is the relevant code in my sample app:

- (void)viewDidLoad
{
    [super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(preferredContentSizeChanged:)
                                                 name:UIContentSizeCategoryDidChangeNotification
                                               object:nil]; 
}

- (void)preferredContentSizeChanged:(NSNotification *)notification
{
    self.testField.font = [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline];
    [self.view setNeedsLayout];
}

If I close the app and reopen it at the big text size, it is fine, until I change it to the small text size, then this starts again. If you just leave it in the same text size for the entire duration of the app, this shift does not occur.

Any ideas how to keep it from shifting like this after the text size is changed?

like image 882
NickH Avatar asked Dec 06 '25 16:12

NickH


1 Answers

The height of your UITextField view isn't tall enough to contain the string at maximum font size.

You have a few options:

  1. Create a taller UITextField
  2. Resize the UITextField at run-time by executing -sizeToFit

PS. Nice animation!

like image 196
SwiftArchitect Avatar answered Dec 08 '25 07:12

SwiftArchitect



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!