Hi this is my first app and I have been trying to figure out how to do this simple task but am getting overloaded with information and I have a feeling there may be an easier way to do it.
I am trying to build a random word generator that will select from an array of words at random time intervals. The time needs to change after the timer fires. The timer can keep running the whole time the app is on.
here is my code so far:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@objc weak var paraTimer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
let randomNum = Int.random(in: 1..<5)
paraTimer = Timer.scheduledTimer(timeInterval: TimeInterval(randomNum), target: self, selector: #selector(runTimedCode), userInfo: nil, repeats: true)
}
/*
This invalidates my timer, not sure if I need to start a new timer now or if I can reset this?
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
paraTimer?.invalidate()
*/
@objc func runTimedCode() {
let array = ["Apple", "Banana", "Pear" ]
label.text = array.randomElement()
}
}
So the issue that I need to fix is it will select a random number from 1-5 and then not select a new number and just keep running every x seconds. Also should I invalidate the timer or leave that off?
Thank you. Like I said, this is my first time working on an app that doesn't just follow a straight tutorial.
Aucun commentaire:
Enregistrer un commentaire