近距离感应

在 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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值