view controller frame size in child controller
Asked Answered
M

1

6

I am implementing UIViewcontroller containment. In the example below I set the frame size of the childcontrollers in the rootcontroller. The child view appears as the size I have set, however when I check on its bounds within container1 it reports a different size to the size I set.

Rootcontroller (container)

- (void)viewDidLoad
{
  [super viewDidLoad];


self.containA = [[Container1 alloc]init];
self.containB = [[Container2 alloc]init];

 self.containA.view.frame = CGRectMake(50, 50,50, 50);
 self.containB.view.frame = CGRectMake(50, 50, 300, 300);

   [self addChildViewController:self.containA];
   [self addChildViewController:self.containB];

  [self.view addSubview:self.containA.view];

Container1

-(void)viewDidLoad {
    [super viewDidLoad];




UIView *view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
//[self.view addSubview:view];
self.view = view;
self.view.backgroundColor = [UIColor redColor];
[view release];
 NSLog(@"view dims %f %f",self.view.bounds.size.width,self.view.bounds.size.height);
}

Console output from container 1 view dims 768.000000 1004.000000

I thought the issue was related to setting the view frame to UIScreen main screen]applicationFrame .So I removed all of this code so the uiview is created automatically. The issue still remains..

Musjid answered 8/7, 2012 at 16:21 Comment(3)
I'm quite confident, btw, that setting self.view inside viewDidLoad is a mistake. Perhaps you are thinking of loadView? developer.apple.com/library/ios/#documentation/uikit/reference/…Martlet
@ctrahey is right, you definitely must not set your view inside of -viewDidLoad. If you are programmatically creating your view instead of using a storyboard or a nib, you must create it and set it -loadView. Also, a view controller should really never change its view's frame. The parent controller or the window always gets to do that.West
thanks for the guidance, so in my case where I have two view controllers nested in a parent, how would I set their size from the parent?I could set it within each controller itself but as you have suggested and I would agree this isn't the most elegant way to do things. Sorry for the 101 questions but Im used to the one view controller per screen, this containment workflow is all new to me.Musjid
M
7

View frames are not actually useable in viewDidLoad; you should move all of your geometry-manipulating code into viewWillAppear. The system will clobber any changes you set in viewDidLoad between there and when it's about tom come on screen.

Martlet answered 8/7, 2012 at 16:27 Comment(2)
Actually, you should move geometry changes to -viewDidAppear pre-iOS 5 and to -viewWillLayoutSubviews for iOS 5+. -viewWillAppear: may not actually have the correct bounds/orientation if the view is being animated.West
Thanks @ctrahey I've been trying to determine just that.Kenlay

© 2022 - 2024 — McMap. All rights reserved.