HovyTech
HovyTech

Reputation: 389

Update UILabel Swift

I have a problem updating my label and can't seem to find any solutions on the Internet. I need the label to update as soon as its text changes. I'm just using a simple observer.

var updateLabel: String = "" {
    didSet { 
        label.text = updateLabel  //This doesn't update
        print(updateLabel)        //This Prints
    }
}

var count: Int? = 0

while (count! < 1000000) {
    count!++
    updateLabel = "\(count!)"
}

I've tried this, but it didn't help.

dispatch_async(dispatch_get_main_queue()) {
}

setNeedsDisplay()

Upvotes: 0

Views: 706

Answers (1)

user4151918
user4151918

Reputation:

By default, controls won't update immediately, but get updated in the next run loop.

Since you are looping a million times, you're blocking updates, and 999,999 of those changes that you are trying to make to the UI won't even be applied.

The last change you make to the UI will not be committed until the run loop gets control.

As an aside, calling setNeedsDisplay only lets the system know that the label needs to be updated in the next run loop. It doesn't update it immediately, as you might think. But it's really superfluous since changing the label's text already marked the label as needing to be updated.

Upvotes: 4

Related Questions