Search code examples
iosobjective-cuiviewautolayoutnslayoutconstraint

Need assistance setting UIButton in centre using Autolayouts


I am trying to programmatically set the UIButton vertically and horizontally in centre using AutoLayouts here is my code:

- (void)awakeFromNib {
UIView *av = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 35.0)];

UIButton *doneButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 37, 30)];

//UIButton title, color, backgroung color, targer action ...

NSLayoutConstraint* cn3 = [NSLayoutConstraint constraintWithItem:doneButton
                                                          attribute:NSLayoutAttributeCenterX
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:av
                                                          attribute:NSLayoutAttributeCenterX
                                                         multiplier:1.0
                                                           constant:0];
    [av addConstraint:cn3];

    NSLayoutConstraint* cn4 = [NSLayoutConstraint constraintWithItem:doneButton
                                      attribute:NSLayoutAttributeCenterY
                                      relatedBy:NSLayoutRelationEqual
                                         toItem:av
                                      attribute:NSLayoutAttributeCenterY
                                     multiplier:1.0
                                       constant:0];
    [av addConstraint:cn4];

[av addSubview:doneButton];
    self.theTextField.inputAccessoryView = av;
}

The above code is working fine except one thing, I am getting this warning in console:

The view hierarchy is not prepared for the constraint: NSLayoutConstraint:0x7fcfc494efb0 UIButton:0x7fcfc2624420'Done'.centerX == UIView:0x7fcfc2624230.centerX

When added to a view, the constraint's items must be descendants of that view (or the view itself). This will crash if the constraint needs to be resolved before the view hierarchy is assembled. Break on -[UIView(UIConstraintBasedLayout) _viewHierarchyUnpreparedForConstraint:] to debug.

And getting same warning for Y.

Please tell me what is going wrong why I am getting this warning?


Solution

  • Add doneButton to the av view before setting your constraints.

    [av addSubview:doneButton];
    
    [av addConstraint:cn3];
    [av addConstraint:cn4];