How to implement UIViewController rotation in response to orientation changes?

前端 未结 4 1186
伪装坚强ぢ
伪装坚强ぢ 2021-01-18 03:14

My app has about 10 different UIViewControllers, just one of which I want to switch to landscape mode if the device is rotated. (All the rest, I want to keep in portrait.)

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-18 03:46

    I have seen examples using the way you are doing it but couldn't get it to work properly. I found the better way to do it from Apples examples. Basically you implement a presentModalViewController and create another view. UIKit does a basic rotation animation and fades between the view. You have to implement the rotated view as a delegate class so it can call back to its calling class to dismiss it and update the orientation.

    - (void)orientationChanged:(NSNotification *)notification
    {
        // We must add a delay here, otherwise we'll swap in the new view
        // too quickly and we'll get an animation glitch
        NSLog(@"orientationChanged");
        [self performSelector:@selector(updateLandscapeView) withObject:nil afterDelay:0];
    }
    

    And then to display a landscape screen:

    - (void)updateLandscapeView
    {
    PortraitView *portraitView = [[PortraitView alloc] init];
    portraitView.delegate = self;
    UIDeviceOrientation deviceOrientation = [UIDevice currentDevice].orientation;
    if (UIDeviceOrientationIsLandscape(deviceOrientation) && !isShowingLandscapeView)
    {
        [self presentModalViewController: portraitView animated:YES];
        isShowingLandscapeView = YES;
        }
    else if (deviceOrientation == UIDeviceOrientationPortrait && isShowingLandscapeView)
    {
        [self dismissModalViewControllerAnimated:YES];
        isShowingLandscapeView = NO;
        }
    [portraitView release];
    }
    

提交回复
热议问题