Calling sizeToFit on a UITextField after changing the font does not work properly on iOS 7.1

Since iOS 7.1, changing the font size and calling sizeToFitdoes not work properly. The text will not be drawn in the correct position and will be cut. The text goes to the correct position when UITextFieldit goes to the first responder. The call resignFirstResponderwill fail again.

enter image description here

Does anyone have a workaround?

- (void)viewDidLoad
{
    [super viewDidLoad];

    UITextField *textField = [[UITextField alloc] init];
    textField.text = @"This is a test";
    textField.backgroundColor = [UIColor redColor];
    [textField sizeToFit]; // Calling this will make the second sizeToFit to fail
    textField.font = [textField.font fontWithSize:textField.font.pointSize * 3];
    [textField sizeToFit];
    textField.center = CGPointMake(self.view.frame.size.width / 2.0, self.view.frame.size.height / 2.0);
    textField.delegate = self;

    [self.view addSubview:textField];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
+4
source share
1 answer

I found a workaround. Changing the text string before calling sizeToFit will make it work correctly:

textField.font = [textField.font fontWithSize:textField.font.pointSize * 3];
NSString *oldText = textField.text;
textField.text = @"";
textField.text = oldText;
[textField sizeToFit];
+7
source

Source: https://habr.com/ru/post/1532382/


All Articles