Search code examples
iosobjective-cios6

Adding a UIButton using NSLayoutConstraint


I have the code below. But I do not see UIButton in the view. Help!

UIButton *addTag = [UIButton buttonWithType:UIButtonTypeRoundedRect];

[_overlayView addSubview: addTag];

[_overlayView setTranslatesAutoresizingMaskIntoConstraints:NO];


[_overlayView addConstraint:[NSLayoutConstraint constraintWithItem:_overlayView
                             attribute:NSLayoutAttributeCenterX
                             relatedBy:NSLayoutRelationEqual
                                toItem:addTag
                             attribute:NSLayoutAttributeCenterX
                            multiplier:1
                              constant:0]];

[_overlayView addConstraint: [NSLayoutConstraint constraintWithItem: _overlayView
                             attribute: NSLayoutAttributeBottom
                             relatedBy: NSLayoutRelationGreaterThanOrEqual
                                toItem:addTag
                             attribute:NSLayoutAttributeBottom
                            multiplier:1
                              constant:20]];

[addTag setTitle:@"Add Tag" forState:UIControlStateNormal];

Do I need to specify the height and width? Isn't there a way this can be automatically set.

If add a [addTag sizeToFit] then a button shows up in the upper left corner.


Solution

  • Well...I took me a day and a half. But I answered my own question.

    I needed to change the translates autoresing mask to constraints to on the button, not on the view.

    [addTag setTranslatesAutoresizingMaskIntoConstraints:NO];
    

    instead of

    [_overlayView setTranslatesAutoresizingMaskIntoConstraints:NO];