How to center a subview
cocoa-touch, ios, objective-c
Solution
Seems like you reposition your view controllers view after centering it. Probably in `didMoveToParentViewController:`.
Move the centering code to the end of `selectRoutine:` method
- (IBAction)selectRoutine:(id)sender
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil];
createRoutinePopupViewController* popupController = [storyboard instantiateViewControllerWithIdentifier:@"createRoutinePopupView"];
[self addChildViewController:popupController];
[self.view addSubview:popupController.view];
[popupController didMoveToParentViewController:self];
//do the centering here
popupController.view.center = [self.view convertPoint:self.view.center fromView:self.view.superview];
}
Or better yet, move it to the `didMoveToParentViewController:`
- (void)didMoveToParentViewController:(UIViewController *)parent
{
//whatever code you have here
self.view.center = self.view.superview.center;
}
Possibly you will have to modify this code a bit. But i'm certain that your problem is incorrect (execution-time-wise) placement of the centering code - that gets subsequently overriden by some other view-positioning.
Problem
I am adding a UIViewController subView to another UIViewController. It works great. But I am having a hard time trying to center the subview in the middle of the parent view. I read up and I found 2 lines of code that worked for other people but its not working for me. Could anyone point out my problem?? those are: `popupController.view.center = [self.view convertPoint:self.view.center fromView:self.view.superview];` and ``` popupController.view.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2); ``` Parent View Controller code: ``` - (IBAction)selectRoutine:(id)sender { UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Storyboard" bundle:nil]; createRoutinePopupViewController* popupController = [storyboard instantiateViewControllerWithIdentifier:@"createRoutinePopupView"]; // popupController.view.center = [self.view convertPoint:self.view.center fromView:self.view.superview]; popupController.view.center = CGPointMake(self.view.bounds.size.width / 2, self.view.bounds.size.height / 2); //Tell the operating system the CreateRoutine view controller //is becoming a child: [self addChildViewController:popupController]; //add the target frame to self's view: [self.view addSubview:popupController.view]; //Tell the operating system the view controller has moved: [popupController didMoveToParentViewController:self]; } ``` child settings