Ben DiMattia Ben DiMattia - 9 months ago 30
Swift Question

Looping Label Change Backround tast in Swift

I'm new to swift and I was looking for a way to loop a changing label that cycles trough an array of Strings. Most ways I've tried have stopped all other tasks while the loop was running.


You're view controller could look something like this:

class ViewController: UIViewController {

    @IBOutlet weak var cycleLabel: UILabel!

    var strings: [String]!
    var timer: NSTimer!
    var index: Int = 0

    override func viewDidLoad() {
        self.strings = ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit", "Vestibulum", "erat", "lacus", "congue"]

    override func viewWillAppear(animated: Bool) {
        self.cycleLabel.text = self.strings[self.index]

    @IBAction func beginCyclingTapped(sender: UIButton) {
        let interval = 1.0

        if self.timer.valid {

        self.timer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: "updateLabel", userInfo: nil, repeats: true)

    func updateLabel() {
        self.index += 1
        self.cycleLabel.text = self.strings[self.index % self.strings.count]


This code will update the label text to the next string in the strings property every one second. If you'd like a different interval, change the interval constant in the beginCyclingTapped(:) method. The label will start restart from the beginning of the strings array after it reaches the last element in that array. The if statement in beginCyclingTapped(:) ensures that multiple timers are not scheduled to update that label, which would result in the label getting updated more frequently than desired. Also, make sure you hook up the IBOutlet to a UILabel on your Storyboard.