0

I am trying to make words in an array show up one at a time on a label, but with my code, the last word in the array shows up. What I want is for my label to display Hello [wait] (a certain amount of time preferably adjustable at some point) World [wait] Testing [wait] Array

Here's my code:

import UIKit

// Variables
let stringOfWords = "Hello World. Say Hello. Test Number One."
let stringOfWordsArray = stringOfWords.components(separatedBy: " ")

class ViewController: UIViewController {
   // Outlets
   @IBOutlet weak var labelWords: UILabel!


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        for word in stringOfWordsArray  {
            labelWords.text=(word)
        }
    }
}

I want to be able to have an adjuster for how fast the words show up and a start and stop button. If anyone can help me with that main part that would be great.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Jon Bergeron
  • 11
  • 1
  • 6

1 Answers1

0

The simplest approach is to use Timer so you will be able to call start/stop it and adjust time (2 seconds in example below):

var timer: Timer?
var wordIndex = 0

override func viewDidLoad() {
    super.viewDidLoad()
    timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}

@objc func update() {
    label.text = stringOfWordsArray[wordIndex]
    if wordIndex < (stringOfWordsArray.count - 1) {
        wordIndex += 1
    }
    else {
        // start again ...
        wordIndex = 0
    }
}

@IBAction func startAction(_ sender: Any) {
    timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}

@IBAction func stopAction(_ sender: Any) {
    // remember to invalidate and nil it when you leave view
    timer?.invalidate()
    timer = nil;
}
Tomasz Czyżak
  • 1,118
  • 12
  • 13