UIDevice类:3-接近传感器proximityState
在iPhone的正面顶部,提供了接近传感器。例如,在接听电话时,当用户的脸部接触手机顶部或者人为使用手指挡住iPhone顶部时,屏幕会自动的熄灭,从而避免误操作。通过UIDevice类中的proximityState属性可以获取当前接近传感器的状态。
接近传感器相关属性
在UIDevice类中,与接近传感器相关的属性如下所示。
- 接近传感器是否生效,默认情况下不生效
@property(nonatomic,getter=isProximityMonitoringEnabled) BOOL proximityMonitoringEnabled;
- 获取接近传感器的工作状态
@property(nonatomic,readonly) BOOL proximityState;
- 系统提供的内置通知,当传感器工作状态发送改变时会触发通知
UIKIT_EXTERN NSString *const UIDeviceProximityStateDidChangeNotification;
示例代码
下方的代码,通过通知机制,来监听当接近传感器启动和关闭时, 打印靠近与离开日志。
- 在viewDidLoad方法中,首先开启接近传感器,默认情况下接近传感器处于关闭状态。同时在通知中心,注册UIDeviceProximityStateDidChangeNotification通知。
- (void)viewDidLoad {
[super viewDidLoad];
UIDevice *device = [UIDevice currentDevice];
//开启接近传感器
device.proximityMonitoringEnabled = YES;
//接近传感器通知
[[NSNotificationCenter defaultCenter] addObserver: self selector:@selector(proximityStateChange) name:UIDeviceProximityStateDidChangeNotification object:nil];
}
- 当收到通知时,触发proximityStateChange方法执行,打印日志。
-(void) proximityStateChange {
UIDevice *device = [UIDevice currentDevice];
if (device.proximityState == YES) {
NSLog(@"物体靠近");
}else {
NSLog(@"物体离开");
}
}
- 移除观察者
-(void)dealloc {
//移除观察者
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
示例代码
https://github.com/99ios/17.1.3
文章发布时间为: October 4th , 2016 at 09:58 am
最后编辑时间为: September 15th , 2017 at 08:08 am
本文由 99ios 创作,转载请注明出处
最后编辑时间为: September 15th , 2017 at 08:08 am
本文由 99ios 创作,转载请注明出处