Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 sizeToFit does not work as expected. The text will be not be drawn at the correct position and will be cut. The text goes to its correct position when the UITextField goes first responder. Calling resignFirstResponder will make it fail again though.

enter image description here

Does anyone have a workaround for that?

- (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;
}
like image 646
rFlex Avatar asked Feb 13 '23 11:02

rFlex


1 Answers

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

textField.font = [textField.font fontWithSize:textField.font.pointSize * 3];
NSString *oldText = textField.text;
textField.text = @"";
textField.text = oldText;
[textField sizeToFit];
like image 141
rFlex Avatar answered Feb 16 '23 04:02

rFlex