Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align a programmatically created UIView's center with an auto-layout view's center

I created an UIView in Storyboard that is to be centered exactly in the center of the View Controller with auto layout, and is working fine across different device sizes. I call this largerView.

However, I would like to programmatically create a smaller UIView called smallerView and center the this view so that smallerView.center = largerView.center.

I am running into an issue where given that auto layout is used on largerView, whenever I use the method above, my smallerView never actually centers with largerView.center. I noticed that it will take the center coordinates of largerView as they appear in Storyboard, based on the specific layout of the device I am using (in this case, the previous iPhone 5's dimensions), but not the updated center as affected by auto layout.

A similar issue may be discussed here, except it is based on Swift. I know how constraints are created programmatically, but am unsure how to get the "refreshed" coordinates of a view after auto layout is applied.

Thanks!

like image 838
daspianist Avatar asked Dec 16 '14 07:12

daspianist


2 Answers

You need to override the following method in your view controller:

- (void)viewDidLayoutSubviews 
{
    [super viewDidLayoutSubviews];
    self.smallView.frame.center = self.largeView.frame.center;
}
like image 171
sha Avatar answered Sep 18 '22 06:09

sha


If your smallerView is subview of largerView:

self.smallerView.center = CGPointMake(self.largerView.frame.size.width / 2, self.largerView.frame.size.height / 2);

If your smallerView have same superview as largerView:

self.smallerView.center = self.largerView.center;
like image 27
Vitalii Gozhenko Avatar answered Sep 21 '22 06:09

Vitalii Gozhenko