如何检测设备的真实方向在视图控制器不旋转在Objective-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];
}

你可以运行CMMotionManager

#import <CoreMotion/CoreMotion.h>
#define DEGREES(x) (180.0 * x / M_PI)
#define RADIAN(x) (M_PI*x/180.0)
#define UPDATE_INTERVAL 0.3
typedef struct Point3D {
CGFloat x, y, z;
} Point3D;
@interface DirectionListener()
{
NSTimer * _motionTimer;
CMMotionManager *_motionManager;
}
@end
@implementation DirectionListener
- (instancetype)init
{
self = [super init];
if (self) 
{
}
return self;
}
- (void)dealloc 
{
[self stopListenning];
_motionManager = nil;
if (_motionTimer) 
{
[_motionTimer invalidate];
_motionTimer = nil;
}
}
- (void)startListenning 
{
if (_motionManager.deviceMotionActive) 
{
return;
}
if (!_motionManager) 
{
_motionManager = [[CMMotionManager alloc] init];
_motionManager.deviceMotionUpdateInterval = UPDATE_INTERVAL;
}
[_motionManager startDeviceMotionUpdates];
if (!_motionTimer) 
{
_motionTimer = [NSTimer scheduledTimerWithTimeInterval:UPDATE_INTERVAL target:self selector:@selector(changeWithAttitude) userInfo:nil repeats:YES];
}
}
- (void)stopListenning {
if (_motionManager.deviceMotionActive) 
{
[_motionManager stopDeviceMotionUpdates];
[_motionTimer invalidate];
_motionTimer = nil;
}
}
-(void)changeWithAttitude 
{
//get the value from motionManager there
}

相关内容

  • 没有找到相关文章

最新更新