NSAutoLayoutConstraints崩溃的应用程序

时间:2015-02-21 03:22:15

标签: ios objective-c nsautolayout

我已经按照了一些教程,但我似乎无法让我的应用程序接受我为NSAutoLayoutConstraints设定的规则。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse constraint format: 
Unable to interpret '|' character, because the related view doesn't have a superview 
V:|-[signupBtn][signupWithFacebookBtn]-| 

在我的viewLoad方法中:

-(void)loadView
{
    [super loadView];



    //Create the background view
    [self.view setBackgroundColor:[UIColor whiteColor]];


    //Set up the buttons, labels, and textfields
    signupBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [signupBtn setTitle:@"Sign Up!" forState:UIControlStateNormal];
    [signupBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    [signupBtn setFrame:CGRectMake(50, 350, 220, 40)];
    signupWithFacebookBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [signupWithFacebookBtn setTitle:@"Sign Up with Facebook" forState:UIControlStateNormal];
    [signupWithFacebookBtn setTranslatesAutoresizingMaskIntoConstraints:NO];
    [signupWithFacebookBtn setFrame:CGRectMake(50, 400, 320, 40)];



    //A dictionary of all subviews
    NSDictionary* m_viewsDictionary = NSDictionaryOfVariableBindings(signupBtn, signupWithFacebookBtn);

    //Constraints
    NSArray* verticalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[signupBtn][signupWithFacebookBtn]-|" options:0 metrics:nil views:m_viewsDictionary];
    NSArray* horizontalConstraints = [NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[signupBtn][signupWithFacebookBtn]-|" options:0 metrics:nil views:m_viewsDictionary];



    //Add the buttons, labels and textfields
    [self.view addSubview:signupBtn];
    [self.view addSubview:signupWithFacebookBtn];

    //Add constraints
    [self.view addConstraints:verticalConstraints];
    [self.view addConstraints:horizontalConstraints];


    NSLog(@"Hello world");
}

我不确定它为什么会崩溃。子视图存在,并且在添加约束之前添加。此外,两个按钮的setTranslatesAutoresizeMaskIntoConstraints都设置为NO。 我错过了什么?

1 个答案:

答案 0 :(得分:22)

在定义约束之前,您应该将按钮添加为子视图 - 解析器不理解“|”是因为您在创建约束时按钮没有超视图。