iOS监听横竖屛通知

2016-09-04  本文已影响483人  小雨雨儿

UIDeviceOrientationDidChangeNotification和UIApplicationDidChangeStatusBarFrameNotification的区别

相同点:UIDeviceOrientationDidChangeNotification和UIApplicationDidChangeStatusBarFrameNotification一样可以监听手机是否横竖屏。
区别: 当全局禁掉自动旋转屏幕的功能后,手机旋转UIApplicationDidChangeStatusBarFrameNotification不会再发出通知。但UIDeviceOrientationDidChangeNotification会发出通知,无论是否支持横竖屏,都会发出通知。这样可以方便的处理横屏后的页面显示问题。
1.注册通知

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeRotate:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
- (void)changeRotate:(NSNotification*)noti {
    if ([[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortrait
        || [[UIDevice currentDevice] orientation] == UIInterfaceOrientationPortraitUpsideDown) {
        //竖屏
        NSLog(@"竖屏");
    } else {
        //横屏
         NSLog(@"横屏");
    }
}

2.两者在监听的方向的多少有区别
UIApplicationDidChangeStatusBarFrameNotification常见的几种情况:

UIDeviceOrientationPortrait  
UIDeviceOrientationPortraitUpsideDown  
UIDeviceOrientationLandscapeLeft  
UIDeviceOrientationLandscapeRight 

UIDeviceOrientationDidChangeNotification

typedef enum {  
    UIDeviceOrientationUnknown,  
    UIDeviceOrientationPortrait,            // Device oriented vertically, home button on the bottom  
    UIDeviceOrientationPortraitUpsideDown,  // Device oriented vertically, home button on the top  
    UIDeviceOrientationLandscapeLeft,       // Device oriented horizontally, home button on the right  
    UIDeviceOrientationLandscapeRight,      // Device oriented horizontally, home button on the left  
    UIDeviceOrientationFaceUp,              // Device oriented flat, face up  
    UIDeviceOrientationFaceDown             // Device oriented flat, face down  
} UIDeviceOrientation; 

单页面需要横屏

//在UIApplication实现该方法
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window {
    if(self.isFull){
        
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
    
}

在需要支持横屏的页面修改isFull的值,并重写方法

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeRotate:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
    AppDelegate * appDelegate = [[UIApplication sharedApplication] delegate];
    appDelegate.isFull = YES;
    
 // 支持设备自动旋转
- (BOOL)shouldAutorotate
{
    return YES;
}
// 支持横竖屏显示
-(UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskAll;
}
上一篇 下一篇

猜你喜欢

热点阅读