什么是Swift的“cleartimeout”等价物?
发布时间:2020-12-14 04:25:08 所属栏目:百科 来源:网络整理
导读:我正在尝试在文本输入字段上设置超时,该字段仅在用户停止输入后的第二秒内实现内部代码.因此,当用户键入时,我会不断调用cleartimeout并重新启动setTimeout. 我最初在Objective C中查看performSelector函数,但看起来没有Swift等价物. 然后我转到Swift中的GCD
我正在尝试在文本输入字段上设置超时,该字段仅在用户停止输入后的第二秒内实现内部代码.因此,当用户键入时,我会不断调用cleartimeout并重新启动setTimeout.
我最初在Objective C中查看performSelector函数,但看起来没有Swift等价物. 然后我转到Swift中的GCD函数,寻找一种执行它的方法. 这是我想出的: var delta: Int64 = 1 * Int64(NSEC_PER_SEC) var time = dispatch_time(DISPATCH_TIME_NOW,delta) dispatch_suspend(dispatch_get_main_queue()) dispatch_after(time,dispatch_get_main_queue(),{ println("timeout") }); dispatch_suspend函数不能像我希望的那样工作. 也许这里的派遣功能不合适? 解决方法
dispatch_after是performSelect的一个很好的替代选择:afterDelay:但我不认为这些都是你想要的(因为一旦你设置它们,就没有办法阻止它们).
如果你想在它闲置一秒后调用一段代码,那么我认为你想要使用一个计时器(例如NSTimer很好,或者你可以使用调度计时器).最重要的是,每次进行键盘交互时,查看是否有待处理的计时器,如果是,则使其无效,然后安排新的计时器. 所以我可能倾向于在S??wift 3中执行类似下面的操作.例如,在iOS 10及更高版本中,您可以使用块再现: weak var timer: Timer? func resetTimer() { timer?.invalidate() timer = .scheduledTimer(withTimeInterval: 1.0,repeats: false) { [weak self] timer in // do whatever you want when idle after certain period of time } } 或者,如果您需要支持没有基于块的计时器的早期iOS版本: weak var timer: Timer? func resetTimer() { timer?.invalidate() timer = .scheduledTimer(timeInterval: 1.0,target: self,selector: #selector(handleIdleEvent(_:)),userInfo: nil,repeats: false) } func handleIdleEvent(_ timer: Timer) { // do whatever you want when idle after certain period of time } 或者,在Swift 2中: weak var timer: NSTimer? func resetTimer() { timer?.invalidate() let nextTimer = NSTimer.scheduledTimerWithTimeInterval(1.0,selector: "handleIdleEvent:",repeats: false) timer = nextTimer } func handleIdleEvent(timer: NSTimer) { // do whatever you want when idle after certain period of time } 顺便说一下,我不确定你对dispatch_suspend的意图是什么,但是不要暂停主队列.你永远不想做任何可能干扰主队列及时处理事件的事情(即永远不会阻塞/暂停主队列). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |