iPhone: Detecting user inactivity/idle time since last screen touch

前端 未结 9 1401
我寻月下人不归
我寻月下人不归 2020-11-22 17:10

Has anybody implemented a feature where if the user has not touched the screen for a certain time period, you take a certain action? I\'m trying to figure out the best way t

9条回答
  •  没有蜡笔的小新
    2020-11-22 17:35

    There's a way to do this app wide without individual controllers having to do anything. Just add a gesture recognizer that doesn't cancel touches. This way, all touches will be tracked for the timer, and other touches and gestures aren't affected at all so no one else has to know about it.

    fileprivate var timer ... //timer logic here
    
    @objc public class CatchAllGesture : UIGestureRecognizer {
        override public func touchesBegan(_ touches: Set, with event: UIEvent) {
            super.touchesBegan(touches, with: event)
        }
        override public func touchesEnded(_ touches: Set, with event: UIEvent) {
            //reset your timer here
            state = .failed
            super.touchesEnded(touches, with: event)
        }
        override public func touchesMoved(_ touches: Set, with event: UIEvent) {
            super.touchesMoved(touches, with: event)
        }
    }
    
    @objc extension YOURAPPAppDelegate {
    
        func addGesture () {
            let aGesture = CatchAllGesture(target: nil, action: nil)
            aGesture.cancelsTouchesInView = false
            self.window.addGestureRecognizer(aGesture)
        }
    }
    

    In your app delegate's did finish launch method, just call addGesture and you're all set. All touches will go through the CatchAllGesture's methods without it preventing the functionality of others.

提交回复
热议问题