Search code examples
iosuitextfieldbounds

UITextfiels bounds, strange behavior


I don't understand what happening with a simple code. I want to resize the width of an UITextField but when I do it, it also changes its origin.x. I tried many configurations but I can't find a solution.

The textfield is in an UIView:

containerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)];
containerView.backgroundColor = [UIColor whiteColor];

textfield = [[UITextField alloc] initWithFrame:CGRectMake(5,20,200,30)];
textfield.leftViewMode = UITextFieldViewModeAlways;

And here is the code for changing its width:

[UIView beginAnimations:nil context:nil];

textfield.bounds = CGRectMake(textfield.bounds.origin.x,
                                  textfield.bounds.origin.y,
                                  textfield.bounds.size.width + 110, 
                                  textfield.bounds.size.height);
[UIView commitAnimations];

Each time, origin.x changes to something like -55 (but NSLog prints 0). Do you have any idea? I would like to maintain always the same origin.x.

Thanks for your help.


Solution

  • Instead of changing the bounds, try changing the frame:

    [UIView beginAnimations:nil context:nil];
    
    textfield.frame= CGRectMake(textfield.frame.origin.x,
                                  textfield.frame.origin.y,
                                  textfield.frame.size.width + 110, 
                                  textfield.frame.size.height);
    [UIView commitAnimations];
    

    From the docs:

    Changing the bounds size grows or shrinks the view relative to its center point
    

    And this seems to be the problem in your case.