根据文本长度更改约束

时间:2016-02-26 11:55:18

标签: ios objective-c nslayoutconstraint nsautolayout

我有两个标签,按照这样排序:

H:[label1]-10-[label2]

我想根据第一个标签的长度更改订单。因此,如果它的文本不适合一行,我想将约束更改为:

V:[label1]-2.5-[label2]

现在我的约束是:

    [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_carLabel]-2.5-[_statusLabel]|" options:0 metrics:nil views:views]];
    [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_carLabel]|" options:0 metrics:nil views:views]];
    [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_statusLabel]|" options:0 metrics:nil views:views]];

_carLabel不符合一行时,这就是我希望他们看的样子:

    [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_carLabel]-10-[_statusLabel]|" options:0 metrics:nil views:views]];
    [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_carLabel]|" options:0 metrics:nil views:views]];
    [self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[_statusLabel]|" options:0 metrics:nil views:views]];

我该怎么做?

1 个答案:

答案 0 :(得分:0)

我认为您最好的选择是根据标签的大小有条件地应用约束。我不相信有一种方法可以添加两种约束,让你按照自己的描述进行操作。 (虽然如果可能的话,它可能与设置每个约束@"[label1]-10@99-[label2]"@"V:[label1]-2.5@98-[label2]的优先级有关,但是我无法让它工作。但是下面的代码似乎就是你做的&# 39;重新寻找。

UILabel *label1 = [[UILabel alloc] init];
    label1.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:label1];
    [label1 setText:@"Small text"];
//    [label1 setText:@"Some really long text to test the other scenario also works"];

    UILabel *label2 = [[UILabel alloc] init];
    label2.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:label2];
    [label2 setText:@"Small text 2"];

    [label1 sizeToFit];
    if (label1.frame.size.width + kPadding + label2.frame.size.width < self.view.frame.size.width) {
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[label1]-padding@100-[label2]"
                                                                         options:0
                                                                          metrics:@{@"padding": @(kPadding)}
                                                                            views:NSDictionaryOfVariableBindings(label1, label2)]];
    } else {
        [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[label1]-2.5@100-[label2]"
                                                options:0
                                                metrics:nil
                                                   views:NSDictionaryOfVariableBindings(label1, label2)]];
    }