SwiftUI how to change a value of @published var
Asked on 09/06/2024
1 search
To change the value of a @Published
variable in SwiftUI, you typically use a @State
or @Binding
property to manage the state within your view. SwiftUI automatically updates the UI when the state changes. Here's a brief explanation based on the context from the "SwiftUI essentials" session:
-
State Management: SwiftUI uses state-driven views, meaning that when your view's state changes, SwiftUI automatically updates the UI. This is achieved using properties like
@State
and@Binding
. -
Using
@State
: You can declare a@State
property in your view to manage its internal state. When you modify this state, SwiftUI will re-render the view to reflect the changes. For example, if you have a button that increments a counter, you would use a@State
property to store the counter value. -
Using
@Binding
: If you need to pass state between views, you can use@Binding
. This creates a two-way connection between a parent view's state and a child view's state, allowing the child view to read and write the parent's state.
Here's a simple example:
struct ContentView: View {
@State private var counter: Int = 0
var body: some View {
VStack {
Text("Counter: \(counter)")
Button("Increment") {
counter += 1
}
}
}
}
In this example, the counter
is a @State
property. When the button is tapped, the counter
is incremented, and SwiftUI automatically updates the Text
view to display the new counter value.
For more detailed information, you can refer to the SwiftUI essentials session, which discusses state management and how SwiftUI handles UI updates.

Enhance your UI animations and transitions
Explore how to adopt the zoom transition in navigation and presentations to increase the sense of continuity in your app, and learn how to animate UIKit views with SwiftUI animations to make it easier to build animations that feel continuous.

What’s new in SwiftUI
Learn how you can use SwiftUI to build great apps for any Apple platform. Explore a fresh new look and feel for tabs and documents on iPadOS. Improve your window management with new windowing APIs, and gain more control over immersive spaces and volumes in your visionOS apps. We’ll also take you through other exciting refinements that help you make expressive charts, customize and layout text, and so much more.

Extend your app’s controls across the system
Bring your app’s controls to Control Center, the Lock Screen, and beyond. Learn how you can use WidgetKit to extend your app’s controls to the system experience. We’ll cover how you can to build a control, tailor its appearance, and make it configurable.