【问题标题】:Adding priority to layout constraints为布局约束添加优先级
【发布时间】:2013-03-12 15:27:44
【问题描述】:

我在superView 中有一个labelbutton,就像这样。

|--------------[Label]-----[button]-|

如果可能的话,我希望label 成为centred,然后与button 保持最小距离,然后向左移动。

所以如果按钮很大,它看起来像......

|-[        LABEL!        ]-[button]-|

因此,按钮将保持原位并保持相同大小。并且元素之间的间隙最小。

我可以添加 centerX 约束,但我似乎无法优先考虑它,所以它仍然是 Required

我怎样才能创造这种情况?我在代码中做所有的自动布局。

我目前的限制是……

[self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|-[_label]-(>=8@1000)-[_button(==45)]-|"
                                                             options:NSLayoutFormatAlignAllCenterY
                                                             metrics:nil
                                                               views:views]];

[self addConstraint:[NSLayoutConstraint constraintWithItem:_label
                                                 attribute:NSLayoutAttributeCenterX
                                                 relatedBy:NSLayoutRelationEqual
                                                    toItem:self.contentView
                                                 attribute:NSLayoutAttributeCenterX
                                                multiplier:1.0
                                                  constant:0.0]];

但我不确定如何降低第二个约束的优先级。

【问题讨论】:

    标签: iphone ios objective-c autolayout


    【解决方案1】:

    您只需设置约束的priority 属性,如下所示:

    NSLayoutConstraint *centeringConstraint = 
        [NSLayoutConstraint constraintWithItem:_label
                                     attribute:NSLayoutAttributeCenterX
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:self.contentView
                                     attribute:NSLayoutAttributeCenterX
                                    multiplier:1.0
                                      constant:0.0];
    
    centeringConstraint.priority = 800; // <-- this line
    
    [self addConstraint:centeringConstraint];
    

    【讨论】:

    • 当然!谢谢!在添加对象之前,我没有想到要创建对象。完美的!现在整理好了,谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    • 2015-10-02
    • 1970-01-01
    相关资源
    最近更新 更多