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!
You need to override the following method in your view controller:
- (void)viewDidLayoutSubviews
{
[super viewDidLayoutSubviews];
self.smallView.frame.center = self.largeView.frame.center;
}
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With