添加NSLayoutConstraint会使视图消失

时间:2014-10-08 04:48:30

标签: ios objective-c cocoa-touch autolayout

我有一个简单的视图(控制器),有两个子视图:

- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *viewA = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    viewA.translatesAutoresizingMaskIntoConstraints = NO;
    viewA.backgroundColor = [UIColor redColor];
    [self.view addSubview:viewA];


    UIView *viewB = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
    viewB.translatesAutoresizingMaskIntoConstraints = NO;
    viewB.backgroundColor = [UIColor grayColor];
    [self.view addSubview:viewB];
}

当然它们在这一点上是重叠的(我只能看到viewB)。所以我添加一个约束来使viewB在viewA下面,如下所示:

[self.view addConstraint:[NSLayoutConstraint constraintWithItem:viewB
                                                      attribute:NSLayoutAttributeTop
                                                      relatedBy:NSLayoutRelationEqual
                                                         toItem:viewA
                                                      attribute:NSLayoutAttributeBottom
                                                     multiplier:1.f
                                                       constant:0]];

这使两个视图都消失了。我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

使用约束时,您应该使用约束(不设置框架)执行所有操作,因此添加一个约束不足以定义位置和大小。我不确定为什么添加一个约束会否定您为视图设置的大小,但似乎确实如此。你应该做这样的事情来完整地描述观点,

- (void)viewDidLoad {
    [super viewDidLoad];

    UIView *viewA = [UIView new];
    viewA.translatesAutoresizingMaskIntoConstraints = NO;
    viewA.backgroundColor = [UIColor redColor];
    [self.view addSubview:viewA];


    UIView *viewB = [UIView new];
    viewB.translatesAutoresizingMaskIntoConstraints = NO;
    viewB.backgroundColor = [UIColor grayColor];
    [self.view addSubview:viewB];
    NSDictionary *dict = NSDictionaryOfVariableBindings(viewA,viewB);

    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[viewA(==50)]" options:0 metrics:nil views:dict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[viewB(==50)]" options:0 metrics:nil views:dict]];
    [self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[viewA(==50)][viewB(==50)]" options:NSLayoutFormatAlignAllLeft metrics:nil views:dict]];
}