iosuitextfieldadaptive-layout

iOS: Correct method to set or increase text field width


Our UITextField instances are using the "default" settings. They auto expand based on user input. We'd like to set them to a larger initial width so they don't have to increase their width. What is the correct way to do this to while maintaining an 'adaptive' layout? Or is this just contrary to iOS best practices and we should leave it as is?


Solution

  • To determine a view's size the autolayout uses two methods:

    - (CGSize)intrisicContentSize //with
    - (UILayoutPriority)contentCompressionResistancePriorityForAxis:(UILayoutConstraintAxis)axis;
    - (UILayoutPriority)contentHuggingPriorityForAxis:(UILayoutConstraintAxis)axis;
    
    and
    
     width and height constrtaints (size constraints)
    //also the autolayot can use inner constraints, but here it is not important
    

    If you have size constraints and intrisic content size with different values, you shout set priority for constraints and for intrisicContentSize.

    In your case, you can set low priority for contentHuggingPriorityForAxis for horizontal axis. Set middle priority for width constraint. Set Hight priority for contentCompressionResistancePriorityForAxis for the horizontal axis. After that, if text be smaller then width constraint, the textField will have width same to constant of the width constraint. Then text will have more width then constraint, the textField will grow out of the width constraint. Also I recommend for you add constraint with "<=" relation for max width and required priority