我正在尝试为我正在使用 Swift 2 开发的应用程序创建超时功能,但在 Swift 2 中,您可以将此代码放入应用程序委托(delegate)中,它可以工作,但它不会检测到任何键盘按下、按钮按下,文本字段按下等:
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];
}
}
上面的代码适用于每次触摸,但 swift 等效代码仅在 UIWindow 层次结构之上不存在 View 时才有效?
有谁知道检测应用程序中每次触摸的方法吗?
最佳答案
因为我的应用程序中有类似的东西,所以我只是试图修复它:
- 覆盖
UIWindow
中的sendEvent
- 不起作用 - 覆盖委托(delegate)中的
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 并添加带有 Principal class 键和 MyApplication
值的行(MyApplication
是里面的内容 @objc(...)
,而不是你的 Swift 类名)。原始 key 是 NSPrincipalClass
。
关于ios - 如何检测 Swift 2 中的所有触摸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31642956/