Align a software-created UIView center with an autoscale view center

I created a UIView in a Storyboard that should be centered exactly in the center of the View Viewer with automatic layout and works great in different device sizes. I call it largerView .

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

I ran into a problem when using largerView using an automatic layout , whenever I use the method above, my smallerView never centered with largerView.center . I noticed that it will take the center coordinates of largerView as they appear on the Storyboard, based on the specific layout of the device I use (in this case, the previous iPhone 5 sizes), but not the updated center, which is affected by the automatic layout.

A similar problem can be discussed here, except that it is based on Swift. I know how constraints are created programmatically, but I'm not sure how to get the "updated" view coordinates after an automatic layout.

Thanks!

+5
source share
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; } 
+8
source

If your smallView is a larger view:

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

If your smallView has the same supervisor as largeView:

 self.smallerView.center = self.largerView.center; 
+7
source

Source: https://habr.com/ru/post/1209200/


All Articles