所以我在Objective-C中找到了这个代码,但是我在Swift中需要它.我尝试了一些方法,但任何方法都有效.所以这是我需要的代码:
- (voID) activateProximitySensor { UIDevice *device = [UIDevice currentDevice]; device.proximityMonitoringEnabled = YES; if (device.proximityMonitoringEnabled == YES) { [[NSNotificationCenter defaultCenter] addobserver:self selector:@selector(proximityChanged:) name:@"UIDeviceProximityStateDIDChangeNotification" object:device]; }}- (voID) proximityChanged:(NSNotification *)notification { UIDevice *device = [notification object]; NSLog(@"Detectat"); //DO WHATEVER I WANT}
编辑1:我试过的是这样的:
overrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() UIDevice.currentDevice().proximityMonitoringEnabled = true; NSNotificationCenter.defaultCenter().addobserver(self,selector: Selector(proximityStateDIDChange()),name:UIDeviceProximityStateDIDChangeNotification,object: nil);}
和功能:
func proximityStateDIDChange() { //DO WHATEVER I WANT}
我在执行应用程序时始终执行的功能.
编辑2:尝试Eric D.评论的代码
let sensor = MySensor() //declared in the VC but globallyoverrIDe func vIEwDIDLoad() { super.vIEwDIDLoad() sensor.activateProximitySensor()}
抛出我的异常:
希望有人能提供帮助,
提前致谢!
这是我对此的看法.func activateProximitySensor() { let device = UIDevice.currentDevice() device.proximityMonitoringEnabled = true if device.proximityMonitoringEnabled { NSNotificationCenter.defaultCenter().addobserver(self,selector: "proximityChanged:",name: "UIDeviceProximityStateDIDChangeNotification",object: device) }}func proximityChanged(notification: NSNotification) { if let device = notification.object as? UIDevice { println("\(device) detected!") }}总结
以上是内存溢出为你收集整理的Swift中的接近传感器(来自Objective-C)全部内容,希望文章能够帮你解决Swift中的接近传感器(来自Objective-C)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)