6

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!

Community
  • 1
  • 1
daspianist
  • 5,336
  • 8
  • 50
  • 94

2 Answers2

8

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

- (void)viewDidLayoutSubviews 
{
    [super viewDidLayoutSubviews];
    self.smallView.frame.center = self.largeView.frame.center;
}
sha
  • 17,824
  • 5
  • 63
  • 98
7

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;
Vitalii Gozhenko
  • 9,220
  • 2
  • 48
  • 66