ios - 通过 Swift 中的触摸检测应用程序何时处于事件状态或非事件状态

标签 ios swift performance optimization uiview

<分区>

什么代码可用于检测用户何时与应用交互以及何时不与应用交互?

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

是否有一个高于一切的手势识别器可以告诉我的应用何时收到手势以及何时没有收到手势?

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

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

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

谢谢。

最佳答案

Swift 2. Xcode 7.2. Tested on iOS 7 - 9.

Adapted from: How to detect all touches in Swift 2 and 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

enter image description here


5 - 运行你的项目!


关于ios - 通过 Swift 中的触摸检测应用程序何时处于事件状态或非事件状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36183377/

相关文章:

ios - 如何获得 linkedin 连接?

ios - 准确的地理位置范围变量

ios - 保护对 NSManaged 对象数组的读/写访问

R:数据表中按行条件求和

生产环境中的 MySQL 变量 innodb_file_per_table 激活

ios - 设置 Collection View 的初始滚动位置

ios - 无法在AppStore中使用原始名称搜索应用

ios - GStreamer 中架构 arm64 的 undefined symbol

objective-c - Swift 中的 EKEventStore enumerateEventsMatchingPredicate

mysql - 获取不同条件下同一列的总和