Detecting rotation to landscape manually

后端 未结 2 1442
野的像风
野的像风 2020-12-08 23:25

I am working on an iPhone application based on UITabBarController and UIViewControllers for each page. The app needs to run in portrait mode only, so every view controller +

相关标签:
2条回答
  • 2020-12-09 00:02

    I needed that in an old project - hope it still works...

    1) Register a notification:

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

    2) Then you can test against the rotation on change:

    -(void) detectOrientation {
        if (([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft) || 
            ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)) {
            [self doLandscapeThings];
        } else if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationPortrait || [[UIDevice currentDevice] orientation] == UIDeviceOrientationPortraitUpsideDown) {
            [self doPortraitThings];
        }   
    }
    

    Hope that helps!

    0 讨论(0)
  • 2020-12-09 00:04

    better code to Comic Sans answer would be below.. His code will not always fire correctly ( only 80% of the time in my testing)

    -(void) detectOrientation {
        if (UIDeviceOrientationIsLandscape([[UIDevice currentDevice] orientation])) {
            [self setupForLandscape];
        } else if (UIDeviceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
            [self setupForPortrait];
        } 
    }
    
    0 讨论(0)
提交回复
热议问题