I have a view controller which is always in portrait. There is a certain feature which works according to the current orientation of the device itself, not orientation of the view controller.
How could I detect the device's orientation and trigger function on orientation changed in this case?
CodePudding user response:
Since iOS 8 they introduced viewWillTransitionToSize
that's triggered every time the rotation happens
- (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];
}
CodePudding user response:
you can achieve this by running 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
}