Detecting rotation to landscape manually

早过忘川 提交于 2019-11-28 07:01:32
Comic Sans

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!

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];
    } 
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!