近距离感应

来源:互联网 发布:ios软件破解论坛 编辑:程序博客网 时间:2024/04/27 14:59

iPhone 近距离传感器的使用

在 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 {

    [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    self.view.backgroundColor = [UIColorredColor];

    //计数器初始为0

    self.countNum = 0;

   

    

    self.label = [[UILabelalloc]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 = [UIColorwhiteColor];

    self.label.textAlignment =1;

//    [self.label setTextAlignment:1];

    

    

    self.label.font = [UIFont systemFontOfSize:60];

    

    [self.labelsetText:[NSStringstringWithFormat:@"%ld",self.countNum]];

    

    [self.viewaddSubview:self.label];

    

    

    

    //获取当前设备,启动近距离感应器

    [[UIDevicecurrentDevice] setProximityMonitoringEnabled:YES];

    //添加通知

    if ([UIDevicecurrentDevice].proximityMonitoringEnabled ==YES) {

        //当近距离传感器状态发生改变的时候发生

        [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(proximitySensorcChange:)name:UIDeviceProximityStateDidChangeNotificationobject:nil];

    }

    

}


- (void)proximitySensorcChange:(NSNotificationCenter *)noti

{

    if ([[UIDevicecurrentDevice] proximityState] ==YES) {

        //再次写接近时候,要做的操作逻辑代码

        NSLog(@"---------");

    }else

    {

        NSLog(@"=====");

        //离开时

        self.countNum++;

        [self.labelsetText:[NSStringstringWithFormat:@"%ld",self.countNum]];

    }

}


- (void)didReceiveMemoryWarning



0 0
原创粉丝点击