iOS - 使用设备方向更改视图

时间:2012-05-30 11:13:08

标签: objective-c ios view orientation-changes

我正在使用iOS5和故事板。我有两个不同的标识符视图。 我想在更改设备的方向时更改视图。 这是我的代码:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {

    if(((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || 
        (interfaceOrientation == UIInterfaceOrientationLandscapeRight))){

        self.view = [self.storyboard instantiateViewControllerWithIdentifier:@"Landscape"];

    }
    else if(((interfaceOrientation == UIInterfaceOrientationPortrait) || 
              (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown))){

        self.view = [self.storyboard instantiateViewControllerWithIdentifier:@"Portrait"];

    }

    return YES;
}

但是应用程序崩溃了。 问题出在哪?

编辑: 如果我添加两个uiview,当我旋转设备时,我将两个id放到uiview中它崩溃了。 这是代码:

- (void)viewDidLoad 
{
    [super viewDidLoad];

    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:@"UIDeviceOrientationDidChangeNotification" object:nil];

}

- (void) orientationChanged:(id)object
{  
    portraitView = [self.storyboard instantiateViewControllerWithIdentifier:@"TermoregolatoreTop"];
    landscapeView = [self.storyboard instantiateViewControllerWithIdentifier:@"Landscape"];

    UIInterfaceOrientation interfaceOrientation = [[object object] orientation];

    if (interfaceOrientation == UIInterfaceOrientationPortrait || interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown) 
    {

        self.view = self.portraitView;
    } 
    else 
    {

        self.view = self.landscapeView;
    }
}

2 个答案:

答案 0 :(得分:0)

self.view = [self.storyboard instantiateViewControllerWithIdentifier:@"Portrait"];

id返回UIViewController并将您分配给UIView

答案 1 :(得分:0)

释放视图控制器时,您必须删除UIDeviceOrientationDidChangeNotification上的观察者。

发生崩溃是因为在类上触发了通知,该通知很可能已从内存中删除。