swift4.2 - 距离传感器

import UIKit

class ViewController: UIViewController {

    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
       
        //开启距离传感器功能
        UIDevice.current.isProximityMonitoringEnabled = true
        
        //监听物体开进或离开设备的通知
        NotificationCenter.default.addObserver(self, selector: #selector(statusChange), name: UIDevice.proximityStateDidChangeNotification, object: nil)
        
    }

    /// 这个主要在 手机上方,电话听筒有相应  = =  下面没得反应
    @objc func statusChange(){
        //获取当前是否有物体靠近设备
        
        if UIDevice.current.proximityState {
            print("大佬来了")
        }else{
            print("大佬走了")
        }
    }
}

  

猜你喜欢

转载自www.cnblogs.com/qingzZ/p/10281320.html