【问题标题】:Swift Timer() will not update label after switching between viewsSwift Timer() 在视图之间切换后不会更新标签
【发布时间】:2017-07-21 15:07:51
【问题描述】:

我正在开发一个非常基本的双视图计时器应用程序,其中在 View1 上我有 30 个按钮(15 个按钮启动计时器,其中 15 个按钮使每个计时器无效),在 View2 上我有一些其他不相关的功能我的问题。

问题是我的用户在定时器仍在运行时在这两个视图之间来回切换 - 在视图之间切换时定时器仍会正常递增,但在来回切换时将停止更新各自的标签.

定时器是这样实现的:

switch timedBehavior {
        case "Introduction":
            timer1 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action), userInfo: nil, repeats: true)

        case "Observing Stationary":
            timer2 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action2), userInfo: nil, repeats: true)

        case "Observing Moving":
            timer3 = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.action3), userInfo: nil, repeats: true)

default:
            print("Error in Timer Button Func")
}

定时器失效按钮实现为:

switch stopButtons {

        case "stpBtn1":
            timer1.invalidate()
        case "stpBtn2":
            timer2.invalidate()
        case "stpBtn3":
            timer3.invalidate()
default:
        print("Error in Stop Button Func")

}

每个定时器都执行这个功能:(增加一个数字并更新一个标签)

func action()
{
    totalTime1 += 1
    timeLabel1.text = String(totalTime1)
}

到目前为止,如果某个特定计时器在viewDidLoad() 中运行,我已经尝试使其无效并立即重新启动它——这实际上似乎创建了两个计时器并将我的增量速度加倍。

不幸的是,我对 Swift 不是很精通,有点不知所措——任何关于更好实现的帮助甚至想法都将不胜感激。谢谢!

【问题讨论】:

  • 你是让viewwilldisappear上的计时器失效还是不需要
  • 您是否使用 segues 在 2 个视图之间进行切换?如果是这样,您应该使用展开转场返回 VC1。
  • @vacawama 我正在使用 segues,是的——没听说过 unwind segue 现在绝对会调查它。
  • 正常的 segue 每次都会创建一个新的目标 VC。因此,您通过在它们之间进行切换来创建越来越多的 VC。这就是为什么您的标签没有更新的原因,因为您正在寻找一个新的 VC1。

标签: ios objective-c swift timer nstimer


【解决方案1】:

您正在使用 segue 在 VC1 和 VC2 之间进行转换。当您从 VC2 返回时,您正在创建一个全新的 VC1,这就是您看不到标签更新的原因。

您应该使用 unwind segue 从 VC2 返回到 VC1。请参阅here 了解如何设置和使用展开转场。

由于您使用滑动手势在视图之间进行切换,因此您需要以编程方式调用 unwind segue。请参阅this answer 的后半部分,了解如何设置 unwind segue 并为其指定一个标识符,以便您可以在滑动处理函数中使用performSegue(withIdentifier:sender:) 调用它。

【讨论】:

  • 正是我需要的 ++ 一些非常棒的参考资料——非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
相关资源
最近更新 更多