Swift Timer() will not update label after switching between views

半世苍凉 提交于 2020-01-03 04:46:08

问题


I have a really basic two-view timer app I'm working on, wherein on View1 I have 30 buttons (15 buttons start timers, 15 of them invalidate each respective timer) and on View2 I have some other functionality not pertinent to my issue.

The issue is that my user switches back and forth between these two views while the timers are still running - the timers will still increment as normal when switching between the views but will cease updating their respective labels once they are switched back and forth.

The timers are implemented as such:

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")
}

The timer invalidating buttons are implemented as:

switch stopButtons {

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

}

And each timer performs this functionality: (increments a number and updates a label)

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

So far I have tried to invalidate and immediately restart a particular timer if it was running in viewDidLoad() - which actually seemingly created two timers and doubled the speed of my increments.

I'm not very well versed with Swift unfortunately and am at a bit of a loss -- any help or even ideas on better implementations would be really appreciated. Thanks!


回答1:


You are using segues to transition between VC1 and VC2. When you return from VC2, you are creating an entirely new VC1 which is why you don't see your labels updating.

You should use an unwind segue to return to VC1 from VC2. See here for how to setup and use an unwind segue.

Since you are using swipe gestures to transition between views, you will need to call the unwind segue programmatically. See the second half of this answer for how to set up the unwind segue and give it an identifier so that you can call it with performSegue(withIdentifier:sender:) from your swipe handler function.



来源:https://stackoverflow.com/questions/42546130/swift-timer-will-not-update-label-after-switching-between-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!