简体   繁体   中英

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!

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM