以编程方式使用NSLayoutConstraint,而不是按照我的预期工作

时间:2014-07-23 01:46:15

标签: ios nslayoutconstraint

我只想要_view2约束它是_view1的底部的顶部,并且差距将是100为好。这是我的代码:

- (void)loadView {
    [super loadView];

    _view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    _view1.backgroundColor = [UIColor blueColor];
    [self.view addSubview:_view1];

    _view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 200, 100, 100)];
    _view2.backgroundColor = [UIColor redColor];
    _view2.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:_view2];

    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:_view2
                                                         attribute:NSLayoutAttributeTop
                                                         relatedBy:NSLayoutRelationEqual
                                                            toItem:_view1
                                                         attribute:NSLayoutAttributeBottom
                                                         multiplier:1 constant:100]];
}

原来是这样的: enter image description here

但我的期望是这样的: enter image description here

1 个答案:

答案 0 :(得分:0)

根据@ borrrden的建议,我刚刚解决了我的问题

只需在宽度和高度上增加两个约束,这是有意义的。

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_view2
                                                      attribute:NSLayoutAttributeWidth
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:_view1
                                                      attribute:NSLayoutAttributeWidth
                                                     multiplier:1 constant:0]];

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:_view2
                                                      attribute:NSLayoutAttributeHeight
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:_view1
                                                      attribute:NSLayoutAttributeHeight
                                                     multiplier:1 constant:0]];