首页 > 解决方案 > 如何在 Objective-C 中不旋转的视图控制器中检测设备的真实方向?

问题描述

我有一个总是纵向的视图控制器。有一个特定的功能根据设备本身的当前方向工作,而不是视图控制器的方向。
在这种情况下,如何检测设备的方向并在方向改变时触发功能?

标签: iosswiftobjective-c

解决方案


自 iOS 8 以来,他们介绍viewWillTransitionToSize了每次旋转发生时都会触发

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {
       [coordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
            // do what you need with orientation here
        } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            
    }];
    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];
}

推荐阅读