本来一般情况可以使用通知来做
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
但是,当用户没有开启屏幕旋转功能时,当前设备是无法接收到通知的,原因就是因为你锁定屏幕之后,系统会默认你当前的屏幕状态一直都是你锁屏时的状态。
目前多大数用户的苹果手机基本都有螺旋仪和加速器,我们可以根据这个东西来判断 这时候就需要先引入CoreMotion.frameWork这个框架,这个框架就是来处理螺旋仪和加速器的东西
@property (nonatomic, strong) CMMotionManager * motionManager;
每隔一个间隔做轮询,调用处理函数
- (void)startMotionManager{
if (_motionManager == nil) {
_motionManager = [[CMMotionManager alloc] init];
}
_motionManager.deviceMotionUpdateInterval = 1/15.0;
if (_motionManager.deviceMotionAvailable) {
NSLog(@"Device Motion Available");
[_motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue currentQueue]
withHandler: ^(CMDeviceMotion *motion, NSError *error){
[self performSelectorOnMainThread:@selector(handleDeviceMotion:) withObject:motion waitUntilDone:YES];
}];
} else {
NSLog(@"No device motion on device.");
[self setMotionManager:nil];
}
}
根据重力感应来判断目前屏幕方向并可以做对应处理
- (void)handleDeviceMotion:(CMDeviceMotion *)deviceMotion{
double x = deviceMotion.gravity.x;
double y = deviceMotion.gravity.y;
if (fabs(y) >= fabs(x))
{
if (y >= 0){
// UIDeviceOrientationPortraitUpsideDown;
}
else{
// UIDeviceOrientationPortrait;
}
}
else
{
if (x >= 0){
// UIDeviceOrientationLandscapeRight;
}
else{
// UIDeviceOrientationLandscapeLeft;
}
}
}
关闭时调用
[_motionManager stopDeviceMotionUpdates];
手动旋转设备
NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeLeft];
[[UIDevice currentDevice] setValue:value forKey:@"orientation"];