iOS开发之传感器

本文介绍了如何使用iOS中的传感器来实现距离感应和设备方向检测。通过监听距离变化和设备朝向,可以实现屏幕自动锁屏和解锁的功能,同时还能获取设备当前的方向状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

iOS开发之传感器

判断当前设备离人或物的距离进行感应

//距离传感器
[UIDevice currentDevice].proximityMonitoringEnabled = YES;

直接上代码

//监听距离感应的通知
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(proximityChange:)
                                             name:UIDeviceProximityStateDidChangeNotification
                                           object:nil];
- (void)proximityChange:(NSNotificationCenter *)notification{

    if ([UIDevice currentDevice].proximityState == YES) {

        NSLog(@"某个物体靠近了设备屏幕"); // 屏幕会自动锁住
    } else {
        NSLog(@"某个物体远离了设备屏幕"); // 屏幕会自动解锁
    }
}

手机方向

[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];

[[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(orientationChanged:)
                                                 name:@"UIDeviceOrientationDidChangeNotification"
                                               object:nil];
- (void)orientationChanged:(NSNotification *)notification{

    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    NSLog(@"当前朝向枚举数字值  %ld",orientation);

    switch (orientation) {

        case UIDeviceOrientationPortrait:
            NSLog(@"portrait ...");             //正立
            break;

        case UIDeviceOrientationPortraitUpsideDown:
            NSLog(@"portrait UpsideDown ...");  //倒立
            break;

        case UIDeviceOrientationLandscapeLeft:
            NSLog(@"Landscape Left ...");       //左横屏
            break;

        case UIDeviceOrientationLandscapeRight:
            NSLog(@"Landscape Right ...");      //右横屏
            break;

        case UIDeviceOrientationFaceUp:
            NSLog(@"Face Up ...");              //平放
            break;

        case UIDeviceOrientationFaceDown:
            NSLog(@"Face Down ...");            //反放
            break;

        default:
            break;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值