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

断了今生、忘了曾经 提交于 2019-12-01 03:35:36

问题


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 the help of Florian Kuglers FLKAutoLayout extensions (https://github.com/dkduck/FLKAutoLayout).

When I set only a leading constraint for the label and a space constraint between label and textfield, the label and textfield widths are adjusted to their content. (bottom picture)

But when I set also a trailing constraint for the textfield, only textfields width is adjusted to its content, but label is stretched. (top picture)

I want to behave the opposite around, so that the textfield will be stretched and the label is adjusted to its content. Why does iOS decide to stretch the label instead of the textfield?

[self addSubview:self.label];
[self addSubview:self.textField];

[self.label alignLeadingEdgeWithView:self predicate:@"10"];
[self.textField constrainLeadingSpaceToView:self.label predicate:@"10"];

// difference between top and bottom pciture
// [self.textField alignTrailingEdgeWithView:self predicate:@"-25"];

回答1:


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"];

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.




回答2:


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.


来源:https://stackoverflow.com/questions/18846033/using-auto-layout-to-have-uilabel-and-uitextfield-next-to-each-other

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!