-(void)viewWillAppear:(BOOL)animated{
UIDevice *device = [UIDevice currentDevice]; //Get the device object
[device beginGeneratingDeviceOrientationNotifications]; //Tell it to start monitoring the accelerometer for orientation
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter]; //Get the notification centre for the app
[nc addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:device];
}
-(void)viewWillDisappear:(BOOL)animated {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
UIDevice *device = [UIDevice currentDevice]; //Get the device object
[nc removeObserver:self name:UIDeviceOrientationDidChangeNotification object:device];
}
- (void)orientationChanged:(NSNotification *)note {
UIDeviceOrientation status= [[UIDevice currentDevice] orientation];
switch (status) {
case UIDeviceOrientationPortrait: // Device oriented vertically, home button on the bottom
[self dismissViewControllerAnimated:YES completion:nil];
break;
case UIDeviceOrientationPortraitUpsideDown: // Device oriented vertically, home button on the top
break;
case UIDeviceOrientationLandscapeLeft: // Device oriented horizontally, home button on the right
;
break;
case UIDeviceOrientationLandscapeRight: // Device oriented horizontally, home button on the left
;
break;
default:
break;
}
}
使用通知监听屏幕的旋转可以有效的避免viewcontrollor判断转向错误的问题
最新推荐文章于 2025-04-28 10:05:19 发布
本文介绍了一个iOS应用如何监听设备的方向变化,并根据不同方向执行相应的操作。通过注册设备方向通知,使用NSNotification来实现对设备方向的监听。
1万+

被折叠的 条评论
为什么被折叠?



