iOS中关闭屏幕旋转功能时如何判断屏幕方向

本来一般情况可以使用通知来做
[[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"];
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • -- iOS事件全面解析 概览 iPhone的成功很大一部分得益于它多点触摸的强大功能,乔布斯让人们认识到手机其实...
    翘楚iOS9阅读 3,223评论 0 13
  • 1、禁止手机睡眠[UIApplication sharedApplication].idleTimerDisabl...
    DingGa阅读 1,211评论 1 6
  • 1、输入若干个数值存入数组中,采用冒泡算法进行升序或降序排序 2、将下图所示,实现转置矩阵matrix.sh1 2...
    张大志的博客阅读 216评论 0 0
  • 讲一个老笑话: 然而这只是现实中的时差。不过是注定太阳先从东方升起,我迎接朝阳,彼仍夜色沉沉,我目送余晖,彼始见晨...
    茕茕踽踽阅读 428评论 0 1
  • 今日如往常不一样,我睡到9点多才起床,不是我贪睡,是室外的大雨困住了我,最喜欢屋外狂风暴雨,屋内安静入睡,那种感觉...
    别看我的心阅读 368评论 0 0

友情链接更多精彩内容