自动布局:UIVabel内部带有填充的UILabel

时间:2015-10-08 12:40:58

标签: ios autolayout uilabel

我试图掌握自动布局,但我很难看到如何实现过去简单明了的事情。我有UILabel *label内在大小,我想放在UIView *container内。标签应该有20个点填充,因此它在容器内垂直和水平居中。

有几个类似的问题指向覆盖intrinsicContentSize方法,但这对于具有多行文本的标签不起作用,并且要求我对标签进行子类化。

我尝试了以下内容:

[self addConstraints:[NSLayoutConstraint
                      constraintsWithVisualFormat:@"H:|-20-[label]-20-|"
                      options:0
                      metrics:nil
                      views:NSDictionaryOfVariableBindings(label)]];

[self addConstraints:[NSLayoutConstraint
                      constraintsWithVisualFormat:@"V:|-20-[label]-20-|"
                      options:0
                      metrics:nil
                      views:NSDictionaryOfVariableBindings(label)]];

确实为容器提供了正确的尺寸,但是如果标签仍位于左上角,则会发出警告。

有人能指出我哪里出错了吗?我确定我还没有 它,但是对于这么简单的任务,自动布局似乎相当复杂。

更新:这是我遇到的2个错误中的一个(第二个是相同的,但是对于垂直约束)。

2015-10-08 13:36:58.869 Thinger[17498:8116452] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints) 
(
    "<NSAutoresizingMaskLayoutConstraint:0x7c23c480 h=--& v=--& UILabel:0x7c140b80'Hello world'.midX == + 38.5>",
    "<NSAutoresizingMaskLayoutConstraint:0x7c2bb500 h=--& v=--& H:[UILabel:0x7c140b80'Hello world'(77)]>",
    "<NSLayoutConstraint:0x7c144b10 H:|-(20)-[UILabel:0x7c140b80'Hello world']   (Names: '|':BigButtonView:0x7c142460 )>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x7c144b10 H:|-(20)-[UILabel:0x7c140b80'Hello world']   (Names: '|':BigButtonView:0x7c142460 )>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

0 个答案:

没有答案