Search code examples
iosobjective-cios7

addChildViewController not working when landscape


I'm using a container view controller to add a subview to my current view controller after 3 seconds:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor = [UIColor greenColor];
    [self performSelector:@selector(open) withObject:nil afterDelay:3.0];
}
-(void)open{
    ViewController2 *test = [[ViewController2 alloc] init];
    test.view.backgroundColor = [UIColor redColor];

    [self addChildViewController:test];
    [self.view addSubview:test.view];
}

ViewController2 is a simple view with just this on the init:

self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

Here is the thing, if I open in portrait the second view and I rotate to landscape, the red color fills the screen, but if I open the second view from landscape, this happens:

enter image description here

Any clues?


Solution

  • Just need to set the frame. The view interface when is open takes the size of the view you projected.

    -(void)open{
        ViewController2 *test = [[ViewController2 alloc] init];
        test.view.backgroundColor = [UIColor redColor];
        test.view.frame = self.view.bounds;
        [self addChildViewController:test];
        [self.view addSubview:test.view];
    }
    

    As a suggestion: start to learn autolayout!