user2636197
user2636197

Reputation: 4122

swift ios change uilabel text value over and over

I have two variable:

var textOne: String = "Some text"
var textTwo: String = "Some other text"

Now I want to assign those values to a UILabel so I loop through them over and over.

Eg. For 5sec MyLabel.text = textOne, then it becomes MyLabel.text = textTwo then it starts over so the text in the label changes every 5 seconds.

Right now I have setup two timers for two functions.

after 5sec this functions will run:

showTextOne() {
MyLabel.text = textOne
}

after 10 sec this function will run:

showTextTwo() {
  MyLabel.text = textTwo
}

But this will only change the label twice and I want to keep it changing between the two values as long as the current VC is displayed.

So is there any other way to keep changing the UILabel.text between two values?

Upvotes: 2

Views: 3131

Answers (3)

jjatie
jjatie

Reputation: 5332

You need a variable to keep track of what the current text is, and then a 5 sec timer that toggles between the two options which can be very simply written like this in Swift 3.

var isTextOne = true

let timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) {
    myLabel.text = isTextOne ? textTwo:textOne
    isTextOne = !isTextOne
}

UPDATE For compatibility with pre iOS 10, watchOS 3, and macOS 10.12 since older versions do not have the block based timers:

var isTextOne = true

func toggleText() {
    myLabel.text = isTextOne ? textTwo:textOne
    isTextOne = !isTextOne
}

let timer = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(toggleText), userInfo: nil, repeats: true)

Upvotes: 5

Maximilian
Maximilian

Reputation: 531

You can accomplish this by using either a timer or a synchronous dispatch queue.

You could for example use the following code to run the task every five seconds using the synchronous dispatch queue method.

let current = 0

func display() {
    let deadline = DispatchTime.now() + .seconds(5)
    DispatchQueue.main.asyncAfter(deadline: deadline) {
        if self.current == 0 {
            MyLabel.text = "Hello world 1."
            self.current == 1
        } else if self.current == 1 {
            MyLabel.text = "Hello World 2."
            self.current == 0
        }
        self.display() // This will cause the loop.
    }
}

Upvotes: 2

Avt
Avt

Reputation: 17043

The easiest way to run some method each 10 seconds is to use NSTimer with repeats = true.

override func viewDidLoad() {
    super.viewDidLoad()
    var timer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(update), userInfo: nil, repeats: true)
}

func update() {
    // Something cool
}

Upvotes: 0

Related Questions