Using Auto Layout to have UILabel and UITextField next to each other

后端 未结 2 607
我寻月下人不归
我寻月下人不归 2021-01-13 09:45

I am trying to position a UILabel instance label next to a UITextField instance textfield like done in the iOS Settings dialogs. I\'m using Auto Layout and constraints with

相关标签:
2条回答
  • 2021-01-13 10:25

    Following constraints which I set in the storyboard works exactly how you want.

    • Horizontal space constraint between label and superview.(default)
    • Horizontal space constraint between textfield and superview. (default)
    • Horizontal space constraint between textfield and label.
    0 讨论(0)
  • 2021-01-13 10:37

    enter image description here

    EDITED: So after the comment of Rahul I played with width and priorities. Adding the following width constraint lead into the somewhat wrong direction, because of entering some very long value, the label was resized too small.

    [self.label constrainWidth:@"0@1"];
    

    enter image description here

    So I finally read up on "Compression Resistance and Content Hugging" (http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html) and the solution is to set the Horizontal Content Hugging priority of the label to a higher value.

    [self.label setContentHuggingPriority:500 forAxis:UILayoutConstraintAxisHorizontal];
    

    Then even entering big values will let the label stay as width as its content!

    Solution is not adding a width constraint with priority, but to set Compression Resistance and Content Hugging properties for the intrinsic content size of the UIViews.

    enter image description here

    0 讨论(0)
提交回复
热议问题