UIWindow子类:触摸事件未被触发

Tap*_*Pal 2 uiwindow touchesbegan ios swift touchesended

我想在当前项目中实现会话时间功能.所以为此我尝试子类化UIWindow并覆盖touchesBegantouchesEnded方法.

class BaseWindow: UIWindow {

    convenience init() {
        self.init(frame: UIScreen.mainScreen().bounds)
    }

    private var sessionTimeOutTimer: NSTimer?

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        sessionTimeOutTimer?.invalidate()
    }

    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        sessionTimeOutTimer = NSTimer.scheduledTimerWithTimeInterval(60, target: CIAppManager.sharedManger(), selector: #selector(CIAppManager.sessionTimeOut), userInfo: nil, repeats: false)
    }
}
Run Code Online (Sandbox Code Playgroud)

在app委托中,我做到了这一点

private let baseWindow = BaseWindow()
var window: UIWindow? {
    get {
        return baseWindow
    }
    set {}
}
Run Code Online (Sandbox Code Playgroud)

但问题是touchesBegan,touchesEnded并没有得到调用.我无法弄清楚我做错了什么.

Leo*_*ica 5

touchesBegan(_:with:)API不会要求你的窗口,除非有没有其他人来捕捉触摸事件.通常情况并非如此,因为您希望UI元素接收触摸.

你想在窗口子类中实现的是sendEvent(:_)将你的逻辑放在那里.不要忘记调用超级实现来传递事件.

使用这种方法的小ceveat是你会听到一些不是触摸事件的事件,但这可能不是问题,因为它们大多是用户生成的.