Update Text in While Loop Swift

Update Text in While Loop Swift

If you want to add a new line of text for each time an if condition is true you need to append the text and use a new line character, \n

while (playerDead != true) {
//...
if playerOnePosition != playerTwoPosition {
labelText.text =
(labelText.text ?? "" ) +
"\(timeStamp) Player One is at \(playerOnePosition) and Player Two is at \(playerTwoPosition)\n"
}

if playerOnePosition == playerTwoPosition {
labelText.text = (labelText.text ?? "" ) + "\(timeStamp) They are in the same place."
playerDead = true
}
}

Also to get your label to display any number of lines set the limit to 0

labelText.numberOfLines = 0

Update Label In While Loop Swift

Try Below Code, this will surely works.

 while (currentSize < fileSize) {

dispatch_sync(dispatch_get_main_queue(), { () -> Void in
downloadLabel.attributedText = NSAttributedString(string: "\(currentSize) kbps", attributes: [NSFontAttributeName: UIFont(name: "Arial", size: 20)!, NSForegroundColorAttributeName: UIColor.darkTextColor()])
});

}

Just paste your UI update code to main thread as shown above.
Reason : You can't update your UI from background thread.

iOS - Swift 5 - Label Text Not Updating within Loop

You didn't explain what the problem is, but I'm going to guess that nothing happens and then the label gets update (finally) to the last value.

That's because sceneTapped is a gesture recognizer, which mean it's running on the main thread. (All UI code and event handling runs on the main thread.)

So sceneTapped is spinning in a loop, on the main thread, queuing up blocks to run on the main thread. But the main thread is busy running sceneTapped so none of those blocks execute.

Finally, sceneTapped returns, and all of those queued blocks suddenly execute, one after the other.

If this for loop is a long running loop, it needs to be running in its own thread. As a rule, you never want to have any code that takes a significant amount to time to execute to be running on the main thread. Any code that blocks the main thread freezes your UI and all user interaction.

So basically you should have something like this:

@objc func sceneTapped(recognizer: UITapGestureRecognizer) {
// ...
DispatchQueue.global().async {
// execute long running code in a background thread
for i in 0...geodesic.count-1 {
// ...

//print(String("\(aircraft.position.x)"))
DispatchQueue.main.async {
//self.dataLabel.setNeedsDisplay()
self.dataLabel.text = String("\(aircraft.position.x)")
}
}
}
}

You want the bulk of the action to run in a background thread, doing its thing, calculating stuff, blocking, waiting, whatever.

When it has something to do with the UI, it can queue a block to run on the main thread, which is still (independently) running, handling events, updating views, recalculating layouts, and generally keeping your app responsive.

Finally, you have to be sure that everything in that background thread is thread safe.

UITextView does not update during loop

You never (well, almost never) want to use sleep().

The reason your text is not updating is because you are running closed-loops that never allow UIKit to update the view.

What you want to do instead is to use a repeating Timer with a one-second interval. Each time the timer fires, decrement your counter and update the UI. When the counter reaches Zero, stop the timer.

Here's a simple example:

import UIKit

let softTime = 5
let medTime = 7
let hardTime = 12

class ViewController: UIViewController {

@IBOutlet weak var timerTextView: UITextView!

var theTimer: Timer?

@IBAction func eggHardnessButton(_ sender: UIButton) {

let hardness = sender.currentTitle
var numSeconds = 0

// set number of seconds based on button title
switch hardness {
case "Soft":
numSeconds = softTime * 60
case "Medium":
numSeconds = medTime * 60
case "Hard":
numSeconds = hardTime * 60
default:
// some other button called this func, so just return
return()
}

// stop current timer if it's running
if let t = theTimer {
if t.isValid {
t.invalidate()
}
}

// update text field with selected time
let timeWord = String(numSeconds)
self.timerTextView.text = timeWord

// start a timer with 1-second interval
theTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { timer in
numSeconds -= 1
let timeWord = String(numSeconds)
self.timerTextView.text = timeWord
// if we've reached Zero seconds remaining
if numSeconds == 0 {
// stop the timer
timer.invalidate()
}
}

}

}

UILabel text not updating inside For loop execution Swift

Your issue not occured in my machine. Please restart your machine, maybe problem will resolve.

Swift update loop

You can set up a timer in viewDidLoad:
first declare it as a variable:

var timer: Timer?

Then in viewDidLoad:

timer = Timer.scheduledTimer(withTimeInterval: 1.0,
repeats: true,
block: { [weak self] _ in
self?.pingHost("http://example.com")
})

How to change a label text during a for loop in IOS swift4?

Define globally.

var count = 0
var timer: Timer?

In viewDidLoad method add timer.

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updating), userInfo: nil, repeats: true)

Outside ViewDidLoad method put below method.

@objc func updating() {
if count >= 100 - 1{
timer?.invalidate()
timer = nil
return
}

count += 1
self.title = "\(count) Task Completed"
}

Actually previously added answer is working fine.

Updating UILabel in the middle of a for() loop

You can make the UI update by telling the run loop to run like this:

for (NSInteger i = 0; i < 10; i++) {
[label setText:...];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
}


Related Topics



Leave a reply



Submit