动态跟踪约束,自动布局以编程方式不起作用

时间:2015-04-08 20:49:00

标签: ios autolayout nslayoutconstraint programmatically-created

我已使用像这样的可视格式以编程方式设置我的约束

[[self contentView] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[label1]-(==space1@1000)-[label2]-(>=space2@750)-|" options:0 metrics:metricsDictionary views:viewDictionary]];

由于我需要[self contentView]label1之间的前导空格是动态的,我创建了一个属性并将其初始化为

[self setLeadingConstraint:[NSLayoutConstraint
                                        constraintWithItem:[self label1]
                                        attribute:NSLayoutAttributeLeading
                                        relatedBy:NSLayoutRelationEqual
                                        toItem:[self contentView]
                                        attribute:NSLayoutAttributeLeading
                                        multiplier:1.0f constant:kLeadingSpace]];

我将所有约束添加到[self contentView],到目前为止工作正常。

这是标签1为长字符串时的外观 Not dynamic trailing space constraint with long string

这是标签1是短字符串时的样子 Not dynamic trailing space constraint with short string

现在我需要将尾随空格作为前导空格动态,所以我尝试了相同的初始化视觉格式约束变量尾随约束,如下所示

[[self contentView] addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[label1]-(==space1@1000)-[label2]" options:0 metrics:metricsDictionary views:viewDictionary]];

[self setTrailingSpaceConstraint:[NSLayoutConstraint
                                                constraintWithItem:[self label2]
                                                attribute:NSLayoutAttributeTrailing
                                                relatedBy:NSLayoutRelationGreaterThanOrEqual
                                                toItem:[self contentView]
                                                attribute:NSLayoutAttributeTrailing
                                                multiplier:1.0f
                                                constant:kTrailingSpace]];

这次没有正确设置尾随约束,因为图像显示

Dynamic trailing space constraint with long string Dynamic trailing space constraint with short string

0 个答案:

没有答案