Home > other >  Trying to use change of button label to exit loop in Swift 5.5 / SwiftUI
Trying to use change of button label to exit loop in Swift 5.5 / SwiftUI

Time:03-29

That is the button code I have been trying to make a button act like a toggle and have a loop run while it is toggled to "Running" and exit the loop when the button returns to "Start"...

@State private var buttonLabel = "Start"

  Button(buttonLabel) {
    if buttonLabel == "Running" {
      buttonLabel = "Start"
    } else {
      buttonLabel = "Running"
    }
    while buttonLabel == "Running" {
      print("running")
    }
  }

I even tried adding under the print statement in the code section of the while statement...

   if buttonLabel != "Running {
    break
   }

When this runs without the while statement...the button will begin showing "Start" and when pressed turns into "Running" and when pressed again returns to "Start". However, when the while loop code is added, when the program is run...when you hit "Start" the text dims and does not show "Running" and there is no way to press the button to turn it back to "Start" or exit the loop.

CodePudding user response:

That's because you are making the main SwfiftUI thread busy with the while. You can run a parallel task if you want to do something inside the while.

struct ButtonProblem: View {
    @State var buttonLabel = "Start"
    var body: some View {
        Button(buttonLabel) {
            if buttonLabel == "Running" {
                buttonLabel = "Start"
            } else {
                buttonLabel = "Running"
            }
            
            Task.detached {
                while buttonLabel == "Running" {
                    print("running")
                    
                }
            }
        }  
    }
}
  • Related