【问题标题】:Make Timer start counting as soon as ViewDidLoad is called调用 ViewDidLoad 后立即让 Timer 开始计数
【发布时间】:2020-08-07 10:36:47
【问题描述】:

我是这样在 ViewDidLoad 中设置 Timer 的:

let timer = Timer.scheduledTimer(
           timeInterval: 3, target: self, selector: #selector(handleAnimation),
       userInfo: nil, repeats: true)

但在它触发第一个 handleAnimation 方法之前,我需要等待 3 秒。 有没有办法让定时器在 viewDidLoad 函数执行后立即触发该函数?

【问题讨论】:

  • 您应该将计时器声明为视图控制器的属性,否则您将无法使其无效。
  • 当我尝试将其声明为 VC 的属性时,我在编译器中收到此错误:由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'-[__SwiftValue handleAnimation]: unrecognized selector sent实例化
  • var timer = Timer() 和你的 viewDidLoad timer = .scheduledTimer(...
  • 谢谢,如果我将其无效,它可以正常工作,但如果我再次触发它就无法正常工作
  • "停止计时器再次触发并请求将其从运行循环中删除" 换句话说,如果您需要再次触发计时器,则需要重新安排它。 "

标签: swift timer viewdidload


【解决方案1】:

立即告诉fire的计时器。

let timer = Timer.scheduledTimer(
       timeInterval: 3, target: self, selector: #selector(handleAnimation),
   userInfo: nil, repeats: true)
timer.fire()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多