实现IOS屏幕旋转监听
可以通过以下步骤实现iOS屏幕旋转监听:
- 在需要监听屏幕旋转的ViewController中,实现以下方法:
- (void)viewWillTransitionToSize:(CGSize)size
withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
[super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
[coordinator animateAlongsideTransition:nil completion:^(id<UIViewControllerTransitionCoordinatorContext> _Nonnull context) {
UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
// 处理屏幕旋转后的操作
}];
}
- 在
viewDidLoad
中添加以下代码,用于启用设备旋转:
//启用设备旋转
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
- 重写
dealloc
方法,在页面销毁时关闭设备旋转:
- (void)dealloc {
[[UIDevice currentDevice] endGeneratingDeviceOrientationNotifications];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- 实现
orientationChanged:
方法,处理设备旋转后的操作:
- (void)orientationChanged:(NSNotification *)noti {
UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
// 处理屏幕旋转后的操作
}
注意:在实现orientationChanged:
方法时,需要注意判断设备旋转的方向,因为设备旋转会有六种方向,即UIDeviceOrientationUnknown
、UIDeviceOrientationPortrait
、UIDeviceOrientationPortraitUpsideDown
、UIDeviceOrientationLandscapeLeft
、UIDeviceOrientationLandscapeRight
、UIDeviceOrientationFaceUp
和UIDeviceOrientationFaceDown
,应根据实际情况选择需要处理的方向。
该博文为原创文章,未经博主同意不得转。本文章博客地址:https://cplusplus.blog.csdn.net/article/details/133968764