views:

14

answers:

1

I have a view controller that alternates 2 views on every touch. Each of the views overrides the drawRect function.

It works when the iPad is in portrait position but for landscape position, the view is shown in the right orientation only once. After that they always appear in portrait orientation.

What's wrong?

In ViewController:

- (void)loadView 
{
 v= [[View2 alloc] init];
 self.view =v;
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
 x++;
 if (x%2==0)
 {
  v= [[View2 alloc] init];
 }
 else {
  v=[[View3 alloc] init];
 }
 self.view = v;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}
A: 

I fixed the problem. It's simple and makes sense. Basically the problem is that only the FIRST view receives orientation events. When changing the view, event handlers must be hooked up again so that the new view can detect the orientation.

An easy fix is to create a dummy view as the parent and add view1 and view2 as subviews. My new controller code is as follow:

- (void)loadView 
{
    self.view =[[UIView alloc] init];

    v= [[View2 alloc] init];
    [self.view addSubview:v];
}

-(void) touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    x++;
    if (v!=NULL)
        [v removeFromSuperview];

    if (x%2==0)
    {
        v= [[View2 alloc] init];

    }
    else {
        v=[[View3 alloc] init];
    }

    [self.view addSubview:v];

}

related questions