I know there are a lot of answers out there about similar issues, but it seems all of them are don't fit to my problem. And I am new to Swift and my head is burning about all this stuff.
The task is very simple. I have a ViewController
and a Class called "TimeIsTicking", which I defined in a separate Swift
File. I did this, because I want to feed 5 ViewController
(which are nested in TabBarController
) with data from the Timer
and they all have to run "synchronized".
The function fireTimer
puts every second the value of 1 to the variable seconds
.
In the ViewController
is a Label
and I want the Label to be updated every time when the timer puts a new value to seconds.
dayLabelText
gets the data, here is everything fine, but from that point I'm stuck. Label Text isn't been updated.
I suspect, that there has to be a "loop" to reload the data for the Label and I thought the loop in fireTimer
would be enough but I was obviously wrong.
I tried the "Observer
Thing" and the "Dispatchqueue
Thing" but I didn't play well ((obviously).
Help would be much appreciated.
Here is the code of the timer class:
import Foundation
import UIKit
class TimeIsTicking {
var seconds: Int = 0
static let timeFlow = TimeIsTicking()
func fireTimer() {
let finance = FinanceVC()
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
self.seconds = 1
finance.dayLabelText = "\(self.seconds)"
print("Seconds: ", self.seconds)
print("LabelText: ", finance.dayLabelText)
}
}
}
And here is the code of the VieWController:
import UIKit
class FinanceVC: UIViewController {
@IBOutlet weak var dayLabel: UILabel!
var dayLabelText = String(TimeIsTicking.timeFlow.seconds)
override func viewDidLoad() {
super.viewDidLoad()
dayLabel.text = dayLabelText
TimeIsTicking.timeFlow.fireTimer()
}
// Do any additional setup after loading the view.
}
CodePudding user response:
I see a few issues:
- The
finance
object goes out of scope whenfireTimer()
returns. It will be deallocated then. The timer will be setting a label text on a no longer existing view controller. - Instantiating a
UIViewController
withFinanceVC()
doesn't display it on screen. After instantiating you need to explicitly show. You can do this for example by calling present(_:animated:completion:) from a parent view controller. - The timer updates
dayLabelText
which does not updatedayLabel.text
Might be good to follow a basic YT tutorial on how to display a view controller.
Good luck, you'll get it soon enough!