How to implement UIViewController rotation in response to orientation changes?

前端 未结 4 1188
伪装坚强ぢ
伪装坚强ぢ 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 04:10

    I do this by having a root view controller (this could be a UITabBarController) and in it's viewDidLoad method i subscribe to rotation events:

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

    Then in the didRotate: method i look at which view controller is visible when the rotation happened, and what orientation the phone is in:

    - (void) didRotate:(NSNotification *)notification { 
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    
    /*
        DEVICE JUST ROTATED TO PORTRAIT MODE
    
     orientation == UIDeviceOrientationFaceUp ||
     orientation == UIDeviceOrientationFaceDown
    
     */
    if(orientation == UIDeviceOrientationPortrait) {
    
    
    
    
    
    /*
        DEVICE JUST ROTATED TO LANDSCAPE MODE
     */
    }else if(orientation == UIInterfaceOrientationLandscapeLeft ||
            orientation == UIInterfaceOrientationLandscapeRight) {
    
    
    
    
    
    
    }
    
    }
    

    Within that didRotate: you can look at which is the visible viewController and do what you want from there.

    I present a modal view controller in landscape mode when a particular view controller is visible and the phone is rotated into landscape. If any other view controller is visible, i ignore the event.

    I force my modal view controller to display in landscape mode in its viewWillAppear method - i can give anyone this code if they want it.

    Hope this helps.

    Dave

提交回复
热议问题