【问题标题】:How to detect screen activity via UIViewController (Swift, iOS 9)如何通过 UIViewController (Swift, iOS 9) 检测屏幕活动
【发布时间】:2016-01-25 21:22:03
【问题描述】:

我想创建一个 UIViewController,它有一个超时时间,它会在一定时间后展开 segue,但会检测何时有屏幕活动并重置计时器。考虑一个密码输入屏幕,如果设备处于空闲状态,您希望屏幕超时。我想 iphone/ipad 将超时,然后当您解锁并返回该应用程序时,我希望在这种情况下也能放松。最好的方法是什么?

【问题讨论】:

    标签: ios swift uiviewcontroller ios9 xcode7


    【解决方案1】:

    定义一个计时器

    var timer = NSTimer() 
    

    在您的viewDidLoad 中将计时器设置为您喜欢的任何值

    这里terminateApp会在60秒后被调用

    timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: Selector("terminateApp"), userInfo: nil, repeats: true)
    
    func terminateApp(){
        // Do your segue and invalidate the timer
        timer.invalidate()
    }
    

    但是如果用户按下你想要使定时器失效并启动一个新定时器的视图,这样做:

    在您的viewDidLoad 中添加一个gestureRecognizer,当用户触摸屏幕时将调用resetTimer:

    let resetTimer = UITapGestureRecognizer(target: self, action: "resetTimer");
    self.view.userInteractionEnabled = true
    self.view.addGestureRecognizer(resetTimer)
    
    func resetTimer(){
        // invaldidate the current timer and start a new one
        timer.invalidate()
        timer = NSTimer.scheduledTimerWithTimeInterval(60, target: self, selector: Selector("terminateApp"), userInfo: nil, repeats: true)
    }
    

    【讨论】:

    • 应用内不活动的最佳答案
    【解决方案2】:

    你可以为UIApplicationDidBecomeActiveNotification注册你的视图控制器

    NSNotificationCenter.defaultCenter().addObserver(self, selector: "yourFunction", name: UIApplicationDidBecomeActiveNotification, object: nil)
    

    或从 AppDelegate 中的 applicationDidBecomeActive 调用视图控制器中的相关函数。

    您还可以在调用applicationDidResignActive 时处理一些事情,在您进入后台而不是返回时执行某些操作。如果用户接听电话等,这具有立即更改的好处,而不是等待计时器。您可以使用计时器方法,在应用仍在屏幕上时处理不活动 - 然后在应用退出活动时使用应用委托方法使计时器无效。

    【讨论】:

      【解决方案3】:

      根据您要支持的交互方式,您有多种选择。

      要检测触摸,您可能希望将您的UIViewControllerview 设置为某个客户UIView 子类,该子类覆盖-hitTest:withEvent:,以向其控制器或其他一些委托报告触摸交互。或者,您可以定义一个手势识别器来报告该视图中的触摸。任何一个都会检测到对控制器子视图的触摸,但不一定是键盘事件(来自不属于控制器视图层次结构的屏幕键盘或硬件键盘)。

      对于键盘事件,您可能需要依赖UITextFieldDelegate,它是-textField:shouldChangeCharactersInRange:replacementString:。我无法立即想到检测这些输入的应用程序或视图范围的方法。

      为了检测设备被锁定或应用失去焦点,您可能需要对UIApplicationWillResignActiveNotification 通知做出反应。

      你想要的那些需要比我从你的问题中提取的更多细节。

      【讨论】:

        猜你喜欢
        • 2018-05-08
        • 1970-01-01
        • 1970-01-01
        • 2017-02-07
        • 1970-01-01
        • 2017-03-02
        • 2012-11-09
        • 1970-01-01
        相关资源
        最近更新 更多