简体   繁体   English

如何检测Swift 2中的所有触摸

[英]How to detect all touches in Swift 2

I'm trying to create a timeout function for an app I'm develop using Swift 2 but in swift 2, you can put this code in the app delegate and it works but it does not detect any keyboard presses, button presses, textfield presses, and etc: 我正在尝试为我正在使用Swift 2开发的应用程序创建超时功能,但在swift 2中,您可以将此代码放在应用程序委托中并且它可以工作,但它不会检测到任何键盘按下,按钮按下,文本字段按下, 等等:

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();
        }
    }
}

Before swift 2, I was able to have the AppDelegate subclass UIApplication and override sendEvent: like this: 在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];
    }
}

The code above works for every touch but the swift equivalent only works when a view does not exist above that UIWindow's hierarchy? 上面的代码适用于每次触摸,但只有在UIWindow的层次结构之上不存在视图时,swift等效项才有效吗?

Does anyone know a way to detect every touch in the application? 有没有人知道检测应用程序中每一次触摸的方法?

As I have something similar in my application, I just tried to fix it: 由于我在我的应用程序中有类似的东西,我只是试图解决它:

  • override sendEvent in UIWindow - doesn't work 覆盖UIWindow sendEvent - 不起作用
  • override sendEvent in delegate - doesn't work 在委托中覆盖sendEvent - 不起作用

So the only way is to provide custom UIApplication subclass. 所以唯一的方法是提供自定义UIApplication子类。 My code so far (works on iOS 9) is: 到目前为止,我的代码(适用于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)
  }

}

Why there's @objc(MyApplication) . 为什么有@objc(MyApplication) That's because Swift mangles names in a different way then Objective-C and it just says - my class name in Objective-C is MyApplication . 那是因为Swift以与Objective-C不同的方式破坏了名称 - 它只是说 - 我在Objective-C中的类名是MyApplication

To make it working, open your info.plist and add row with Principal class key and MyApplication value ( MyApplication is what's inside @objc(...) , not your Swift class name). 要使其工作,请打开info.plist并添加具有Principal类键和MyApplication值的行( MyApplication@objc(...)内部的@objc(...) ,而不是您的Swift类名称)。 Raw key is NSPrincipalClass . 原始密钥是NSPrincipalClass

在此输入图像描述

UIWindow also has a sendEvent method that you can override. UIWindow还有一个可以覆盖的sendEvent方法。 That would allow you to track the time since the last screen touch. 这样您就可以跟踪自上次触摸屏幕以来的时间。 Swift 4: 斯威夫特4:

class IdlingWindow: UIWindow {
    /// Tracks the last time this window was interacted with
    var lastInteraction = Date.distantPast

    override func sendEvent(_ event: UIEvent) {
        super.sendEvent(event)
        lastInteraction = Date()
    }
}

If you're using a storyboard, you can load it in didFinishLaunchingWithOptions : 如果您正在使用故事板,则可以在didFinishLaunchingWithOptions加载它:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: IdlingWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        window = IdlingWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = UIStoryboard.init(name: "Main", bundle: nil).instantiateInitialViewController()
        window?.makeKeyAndVisible()
        return true
    }
    :
}

extension UIApplication {
    /// Conveniently gets the last interaction time
    var lastInteraction: Date {
        return (keyWindow as? IdlingWindow)?.lastInteraction ?? .distantPast
    }
}

Now elsewhere in your app, you can check for inactivity like this: 现在您的应用程序中的其他位置,您可以检查不活动,如下所示:

if UIApplication.shared.lastInteraction.timeIntervalSinceNow < -2 {
    // the window has been idle over 2 seconds
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM