在 iOS 中,并非所有 iOS 设备都拥有近距离传感器。这里介绍如何调用 iPhone 的距离传感器。
使用近距离传感器
UIDevice 中有两个近距离传感器的属性:proximityMonitoringEnabled 和 proximityState。这两个属性都是 iOS 3.0 及以上才支持的。
proximityMonitoringEnabled 属性
To determine if proximity monitoring is available, attempt to enable it. If the value of the proximityState property remains NO, proximity monitoring is not available.
要确定近距离传感器是否可用,可以尝试启用它,即 proximityMonitoringEnabled = YES,如果设置的属性值仍然为NO,说明传感器不可用。
proximityState 属性
传感器已启动前提条件下,如果用户接近 近距离传感器,此时属性值为YES,并且屏幕已关闭(非休眠)。And vice versa。
Notification
UIDeviceProximityStateDidChangeNotification,当近距离传感器状态改变时发生。
下面我们看看代码部分:
#import "ViewController.h"
@interface ViewController ()
//
@property(nonatomic,retain)UILabel *label;
//计数器
@property(nonatomic,assign)NSInteger countNum;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor redColor];
//计数器初始为0
self.countNum = 0;
self.label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 160, 160)];
//圆行得label
self.label.layer.masksToBounds = YES;
//弧度
self.label.layer.cornerRadius = 80;
//视图中心点
self.label.center = CGPointMake(160, 250);
self.label.backgroundColor = [UIColor whiteColor];
self.label.textAlignment = 1;
// [self.label setTextAlignment:1];
self.label.font = [UIFont systemFontOfSize:60];
[self.label setText:[NSString stringWithFormat:@"%ld",self.countNum]];
[self.view addSubview:self.label];
//获取当前设备,启动近距离感应器
[[UIDevice currentDevice] setProximityMonitoringEnabled:YES];
//添加通知
if ([UIDevice currentDevice].proximityMonitoringEnabled == YES) {
//当近距离传感器状态发生改变的时候发生
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(proximitySensorcChange:) name:UIDeviceProximityStateDidChangeNotification object:nil];
}
}
- (void)proximitySensorcChange:(NSNotificationCenter *)noti
{
if ([[UIDevice currentDevice] proximityState] == YES) {
//再次写接近时候,要做的操作逻辑代码
NSLog(@"---------");
}else
{
NSLog(@"=====");
//离开时
self.countNum++;
[self.label setText:[NSString stringWithFormat:@"%ld",self.countNum]];
}
}
- (void)didReceiveMemoryWarning