Search code examples
iosiphoneobjective-cuiviewautolayout

Resizing a UITextField programmatically automatically reverts back to old size


After a certain user action I wish to resize a UITextField and move it to the right: e.g.

CGRect oldFrame = self.sampleTextField.frame;
CGRect newFrame = CGRectMake(oldFrame.origin.x + 100,
                             oldFrame.origin.y, 
                             oldFrame.size.width - 100, 
                             oldFrame.size.height);
[self.sampleTextField setFrame:newFrame];

This works for about half a second and then the UITextField snaps back into it's original, unedited frame.

The UITextField is put in place in a storyboard but I have removed all auto-layout constraints from it.

Is it auto-layout that is returning the UITextField to it's original frame?

Is there a way of achieving this with my current setup or will I have to take the UITextField out of the storyboard and programmatically add it to the View?


Solution

  • If you build and run without adding any constraints to an element, you’ll find that Interface Builder fixes the element’s width and height, and pins its position relative to the top left corner of the superview.

    To make your interface react correctly to changes in size or orientation, you need to start adding constraints. You can also remove the automatically added constraints programmatically before you set the frame and set translatesAutoresizingMaskIntoConstraints to NO.