2014-10-08 24 views
1

我有一個簡單視圖(控制器)具有兩個子視圖:加入NSLayoutConstraint使得視圖消失

- (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

使用約束條件時,您應該儘可能使用約束條件(不設置框架),因此添加一個約束條件不足以定義您的位置和大小。我不確定爲什麼添加一個約束會否定您爲視圖設置的大小,但它似乎確實如此。你應該這樣做,以充分描述意見,

- (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]]; 
} 
+0

非常感謝! – 0xSina 2014-10-08 05:53:03