在以编程方式添加UIConstraints时不应用尾随约束

时间:2017-02-03 10:35:41

标签: ios objective-c autolayout

我试图通过代码将约束添加到具有约束的视图中。我取得了一些成功,但无论出于何种原因,尾随约束似乎都被完全忽略了。

我的代码:

leading_const = 16.f;
trailing_const = 16.f;
top_const = 12.f;
bottom_const = 12.f;


insertView.translatesAutoresizingMaskIntoConstraints = NO;
[view addSubview:insertView];
NSLayoutConstraint *leading = [NSLayoutConstraint constraintWithItem:insertView
                                                           attribute:NSLayoutAttributeLeading
                                                           relatedBy:NSLayoutRelationEqual
                                                              toItem:view
                                                           attribute:NSLayoutAttributeLeading
                                                          multiplier:1.f
                                                            constant:leading_const];
NSLayoutConstraint *trailing = [NSLayoutConstraint constraintWithItem:insertView
                                                            attribute:NSLayoutAttributeTrailing
                                                            relatedBy:NSLayoutRelationEqual
                                                               toItem:view
                                                            attribute:NSLayoutAttributeTrailing
                                                           multiplier:1.f
                                                             constant:trailing_const];
NSLayoutConstraint *top = [NSLayoutConstraint constraintWithItem:insertView
                                                       attribute:NSLayoutAttributeTop
                                                       relatedBy:NSLayoutRelationEqual
                                                          toItem:view
                                                       attribute:NSLayoutAttributeTop
                                                      multiplier:1.f
                                                        constant:top_const];
NSLayoutConstraint *height = [NSLayoutConstraint constraintWithItem:insertView
                                                                   attribute:NSLayoutAttributeHeight
                                                                   relatedBy:NSLayoutRelationEqual
                                                                      toItem:nil
                                                                   attribute:NSLayoutAttributeHeight
                                                                  multiplier:1.f
                                                                    constant:130.f];
[superView addConstraints:@[leading, trailing, top, height]];

结果:

enter image description here

感谢任何指导!

1 个答案:

答案 0 :(得分:7)

您的约束正在应用,但是当您将其设置为16时,它将超过view的后缘16个点。因此,您应该使用常量的负值。