Search code examples
iosobjective-cuitextfieldautoresizingmask

How to set a text field for fixed left margin & flexible right margin using auto resizing mask programmatically


I want my text field to have a fixed left side margin & flexible right side margin in all orientations. Left side fixed margin is working well but right side flexible margin is not working properly. Here is my code

tf.frame=CGRectMake(startX, startY, [UIScreen mainScreen].bounds.size.width-40, 44);
[tf setAutoresizingMask:UIViewAutoresizingFlexibleWidth];

The issue is that when I use UIViewAutoresizingFlexibleWidth it is not considering the gap of 40px I am providing for setting text field width & text field is taking full screen width as its dimensions.


Solution

  • If you want a flexible right margin, set the mask that way:

    tf.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
    

    But I suspect you have other problems. You're setting the text fields bounds based on the main screen's size. The main screen's size may not have anything to do with the size of the text field's superview, depending on when that code runs.