您的位置:首页 > 其它

29.iPhone距离传感器的简单使用

2015-12-27 17:11 483 查看
上一章, 我们知道了陀螺仪传感器的使用方法, 现在让我们来看看下一个传感器, 距离传感器.

PS: 已经更新到Swift 2.1, 支持iOS 9.1

1.实现代码

[code]import UIKit
import CoreMotion

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func viewWillAppear(animated: Bool) {
        // 1.打开距离传感器
        UIDevice.currentDevice().proximityMonitoringEnabled = true

        // 2.设置一个通知, 一旦距离传感器被使用, 就调用自定义的proximatyChanged方法
        NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("proximatyChanged"), name: UIDeviceProximityStateDidChangeNotification, object: nil)
    }

    // 3.自定义proximatyChanged方法
    func proximatyChanged() {
        print(">>>>>")
        print("\(UIDevice.currentDevice().proximityState)")
    }

    // 4.关掉页面之后, 把通知删除
    override func viewDidDisappear(animated: Bool) {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}


2.最终效果



项目地址: 链接: http://pan.baidu.com/s/1i3g0A9Z 密码: qp8c
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: