通过 Swift 中的触摸检测应用程序何时处于活动状态或不活动状态[重复]

2024-01-17

可以使用哪些代码来检测用户何时与应用程序交互以及用户何时不与应用程序交互?

目前我有一个ViewController with a UIView即通过覆盖触摸来接收触摸,也通过接收平移手势和点击手势来接收触摸。此问题的解决方案需要与当前的手势分开或位于这些手势之上。

是否有一个手势识别器位于最重要的位置,可以告诉我的应用程序何时收到手势以及何时没有收到手势?

当应用程序处于活动状态时,是否有一种方法可以监视应用程序是否正在接收触摸以及何时没有接收触摸,并根据需要调用函数,例如:

func appActive(){
    print("App received input from a touch, tap, swipe, long press etc.")
}

func appInactive(){
    print("App stopped receiving any input.")
}

谢谢。


斯威夫特 2.Xcode 7.2。在 iOS 7 - 9 上测试。

改编自: 如何在 Swift 2 中检测所有触摸 https://stackoverflow.com/questions/31642956/how-to-detect-all-touches-in-swift-2 and 使用 Swift 子类化 UIApplication https://stackoverflow.com/questions/24020000/subclass-uiapplication-with-swift


1 - 找到项目的 Swift 文件AppDelegate.swift,并注释掉@UIApplicationMain:

//@UIApplicationMain

2 - 将新的 Swift 文件添加到您的项目中,并命名为main.swift,并添加代码:

import UIKit

UIApplicationMain(  
CommandLine.argc, UnsafeMutableRawPointer(CommandLine.unsafeArgv)  
    .bindMemory( to: UnsafeMutablePointer<Int8>.self,  
        capacity: Int(CommandLine.argc)), nil, NSStringFromClass(AppDelegate.self))  

3 - 将一个新的 Swift 文件添加到您的项目中,并命名为UIApplication.swift,并添加代码:

import UIKit

@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 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 timer
            print("Touches ended. Restart timer")
        } else {
            // Touches in progress - !ended, !cancelled, just invalidate it
            print("Touches in progress. Invalidate timer")
        }
    
        super.sendEvent(event)
    }
}

4 - 找到您的项目Info.plist文件,并添加一个新密钥(Xcode 菜单:Editor > Add Item)、选择或键入键Principal class,带有字符串值MyApplication.


5 - 运行您的项目!


本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过 Swift 中的触摸检测应用程序何时处于活动状态或不活动状态[重复] 的相关文章

随机推荐