import SwiftUI
struct MainActorDemoView: View {
@State private var labelText = "Waiting..."
var body: some View {
VStack(spacing: 20) {
Text(labelText)
.font(.title)
Button("Update Label") {
updateLabel()
}
}
.padding()
}
func updateLabel() {
Task {
try? await Task.sleep(nanoseconds: 2_000_000_000) // 2 seconds
await MainActor.run {
labelText = "Updated on MainActor!"
}
}
}
}
struct MainActorDemoView_Previews: PreviewProvider {
static var previews: some View {
MainActorDemoView()
}
}We use Task to run an asynchronous background task that simulates a 2-second delay using Task.sleep. After the delay, we update the labelText state variable on the main thread by calling await MainActor.run. This ensures the UI update happens safely on the main thread, which is required for SwiftUI views.
The button calls updateLabel() when tapped, triggering the background wait and then the UI update.