0
0
iOS Swiftmobile~5 mins

MainActor for UI updates in iOS Swift

Choose your learning style9 modes available
Introduction

We use MainActor to make sure UI changes happen on the main thread. This keeps the app smooth and avoids crashes.

When updating labels or buttons after fetching data.
When changing the screen after a user taps a button.
When showing or hiding loading indicators.
When modifying any UI elements from background tasks.
Syntax
iOS Swift
@MainActor
func updateUI() {
  // UI code here
}

@MainActor marks a function or class to run on the main thread.

This helps keep UI updates safe and smooth.

Examples
This function updates a label's text safely on the main thread.
iOS Swift
@MainActor
func refreshLabel() {
  label.text = "Hello!"
}
Marking a method inside a class with @MainActor ensures UI changes happen on the main thread.
iOS Swift
class ViewModel {
  @MainActor
  func updateButton() {
    button.isEnabled = true
  }
}
Sample App

This SwiftUI app shows a message and a button. When you tap the button, it waits 1 second and updates the message safely on the main thread using @MainActor.

iOS Swift
import SwiftUI

@MainActor
class ViewModel: ObservableObject {
  @Published var message = "Loading..."

  func loadData() async {
    // Simulate background work
    try? await Task.sleep(nanoseconds: 1_000_000_000)
    message = "Data loaded!"
  }
}

struct ContentView: View {
  @StateObject private var vm = ViewModel()

  var body: some View {
    VStack {
      Text(vm.message)
        .padding()
      Button("Load Data") {
        Task {
          await vm.loadData()
        }
      }
    }
  }
}
OutputSuccess
Important Notes

Always update UI on the main thread to avoid bugs.

@MainActor is an easy way to do this in Swift concurrency.

You can mark whole classes or individual functions with @MainActor.

Summary

MainActor ensures UI updates run on the main thread.

Use it when changing anything visible on screen.

It helps keep your app smooth and crash-free.