您可以通过检测 iPhone 的 ProximityState 来完成此操作。使用[UIDevice currentDevice]
单例,设置proximityMonitoringEnabled
为YES
. 您可以通过proximityState 属性访问接近度信息。
[[UIDevice currentDevice]proximityState];
iPhone 有一个传感器,当您在通话期间将其戴在耳朵上时,它会关闭屏幕,AFAIK 是一个红外传感器。你可以访问它。
编辑:您也可以使用以下代码完成它。UIDeviceOrientationFaceDown
The device is held parallel to the ground with the screen facing downwards.
(不管它是否触摸了任何物体)如果您想知道 iPhone 是否触摸了一个物体,请检测设备的接近状态。
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(detectOrientation) name:@"UIDeviceOrientationDidChangeNotification" object:nil];
-(void)detectOrientation;{
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;
default:
break;
}
}
}
编辑:回答评论中的问题。在您的 viewDidLoad 中添加这一行
[UIDevice currentDevice].proximityMonitoringEnabled = YES;
[[NSNotificationCenter defaultCenter] removeObserver:self];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleProximityChangeNotification:) name:UIDeviceProximityStateDidChangeNotification object:nil];
然后写一个方法
-(void)handleProximityChangeNotification{
if([[UIDevice currentDevice]proximityState]){
NSLog(@"...");
}
}