在最近的一个项目中,想实现一个翻转iPhone屏幕触发事件的交互。
1、最开始想到的方法是去检测设备的方向,代码如下:
//打开设备加速计,检测方向变化
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
//注册一个通知,接收变化,做出相应操作
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkOrientation) name:UIDeviceOrientationDidChangeNotification object:nil];
实现接收到通知方法:
- (void)checkOrientation
{
switch ([[UIDevice currentDevice] orientation]) {
case UIDeviceOrientationPortrait:
NSLog(@"portrait");
break;
case UIDeviceOrientationPortraitUpsideDown:
NSLog(@"portraitUpSideDown");
break;
case UIDeviceOrientationLandscapeLeft:
NSLog(@"landscapeLeft");
break;
case UIDeviceOrientationLandscapeRight:
NSLog(@"landscapeRight");
break;
case UIDeviceOrientationFaceDown:
NSLog(@"facedown!!");
break;
case UIDeviceOrientationFaceUp:
NSLog(@"FaceUp");
break;
default:
break;
}
}
这个方法能够实现监听屏幕正面朝上还是背面朝上,但是有个问题,如果用户关闭了 屏幕旋转,这个方法不会生效!
2、在听筒旁边有一个距离感应器,在打电话的时候,离开耳朵屏幕亮起,靠近耳朵屏幕熄灭就是用到了这个距离感应器,同理,可以用这个方式来检测判断屏幕是否翻转。
//打开距离监控器,官方文档做了说明:不是所有的iOS设备都距离感应传感器,如果属性proximityMonitoringEnabled始终为假,将不能使用此功能
[[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(sensorStateChange:) name:UIDeviceProximityStateDidChangeNotification object:nil];
实现接收到通知的方法:
- (void)sensorStateChange:(NSNotificationCenter *)notification;
{
if ([[UIDevice currentDevice] proximityState] == YES)
{
NSLog(@"黑屏了");
//屏幕翻转干的事
}
else
{
NSLog(@"屏幕亮了");
}
}
在做测试的时候遇到一个问题,就是将屏幕转到正面朝上后有时候屏幕不会亮起,经过测试,大概是15秒左右,超过15秒屏幕不会亮起,不知道是什么原因,感兴趣的小伙伴可以做一下测试,欢迎留言指导!