Center custom UIView vertically and horizontally using Auto Layout Center custom UIView vertically and horizontally using Auto Layout ios ios

Center custom UIView vertically and horizontally using Auto Layout


Try adding a height and width constraint to your circle_view. I couldn't even get just a pain square view to appear at all without adding those (using your code, minus the layer stuff).

NSLayoutConstraint *heightConstraint =    [NSLayoutConstraint constraintWithItem:circle_view                                 attribute:NSLayoutAttributeHeight                                 relatedBy:NSLayoutRelationEqual                                    toItem:nil                                 attribute:NSLayoutAttributeNotAnAttribute                                multiplier:1.0                                  constant:100.0];    [circle_view addConstraint:heightConstraint];    NSLayoutConstraint *widthConstraint =    [NSLayoutConstraint constraintWithItem:circle_view                                 attribute:NSLayoutAttributeWidth                                 relatedBy:NSLayoutRelationEqual                                    toItem:nil                                 attribute:NSLayoutAttributeNotAnAttribute                                multiplier:1.0                                  constant:100.0];    [circle_view addConstraint:widthConstraint];


Just to add to rdelmar's answer:

The core issue is that as soon as you go the NSLayoutConstraint route, and specify setTranslatesAutoresizingMaskIntoConstraints:NO, the frame you made with CGRectMake is rendered irrelevant for AutoLayout purposes. That's why it didn't use the info from the frame's height and width.