如何检测Swift 2中的所有触摸
我试图创build一个应用程序,我使用Swift 2开发的超时function,但在迅速2,你可以把这个代码在应用程序委托,它的工作原理,但它没有检测到任何键盘按下,按下button,文本字段按, 等等:
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { super.touchesBegan(touches, withEvent: event); let allTouches = event!.allTouches(); if(allTouches?.count > 0) { let phase = (allTouches!.first as UITouch!).phase; if(phase == UITouchPhase.Began || phase == UITouchPhase.Ended) { //Stuff timeoutModel.actionPerformed(); } } }
在swift 2之前,我能够拥有AppDelegate子类UIApplication并覆盖sendEvent:像这样:
-(void)sendEvent:(UIEvent *)event { [super sendEvent:event]; // Only want to reset the timer on a Began touch or an Ended touch, to reduce the number of timer resets. NSSet *allTouches = [event allTouches]; if ([allTouches count] > 0) { // allTouches count only ever seems to be 1, so anyObject works here. UITouchPhase phase = ((UITouch *)[allTouches anyObject]).phase; if (phase == UITouchPhaseBegan || phase == UITouchPhaseEnded) [[InactivityModel instance] actionPerformed]; } }
上面的代码适用于每一个触摸,但只有当一个视图不存在于UIWindow的层次结构之上时,swift才会起作用。
有没有人知道一种方法来检测应用程序中的每一个接触?
正如我在应用程序中有类似的东西,我只是试图解决它:
- 覆盖
UIWindow
sendEvent
– 不起作用 - 重写
sendEvent
中的sendEvent
– 不起作用
所以唯一的办法是提供自定义的UIApplication
子类。 我的代码到目前为止(适用于iOS 9)是:
@objc(MyApplication) class MyApplication: UIApplication { override func sendEvent(event: UIEvent) { // // Ignore .Motion and .RemoteControl event // simply everything else then .Touches // if event.type != .Touches { super.sendEvent(event) return } // // .Touches only // var restartTimer = true if let touches = event.allTouches() { // // At least one touch in progress? // Do not restart auto lock timer, just invalidate it // for touch in touches.enumerate() { if touch.element.phase != .Cancelled && touch.element.phase != .Ended { restartTimer = false break } } } if restartTimer { // Touches ended || cancelled, restart auto lock timer print("Restart auto lock timer") } else { // Touch in progress - !ended, !cancelled, just invalidate it print("Invalidate auto lock timer") } super.sendEvent(event) } }
为什么有@objc(MyApplication)
。 这是因为Swift以不同的方式改变了名字,然后Objective-C,它只是说 – 我在Objective-C中的类名是MyApplication
。
为了使它工作,打开你的info.plist并添加具有主体类键和MyApplication
值的行( MyApplication
是@objc(...)
,而不是你的Swift类名)。 原始密钥是NSPrincipalClass
。