Skip to main content

How to create constant bindings

About 2 minSwiftSwiftUIArticle(s)bloghackingwithswift.comcrashcourseswiftswiftuixcodeappstore

How to create constant bindings 관련

SwiftUI by Example

Back to Home

How to create constant bindings | SwiftUI by Example

How to create constant bindings

Updated for Xcode 15

When you're prototyping some UI, or when you just need to pass in a value to give your SwiftUI preview something meaningful to show, you will find it helpful to use constant bindings: hard-coded values that don't change, but can still be used like regular bindings so your code works.

For example, if you want to create a toggle switch you would normally have to create an @State property to store the Boolean, then send that into the toggle switch when you create it. However, if you're just prototyping your user interface you can use a constant binding instead, like this:

Toggle(isOn: .constant(true)) {
    Text("Show advanced options")
}

Download this as an Xcode projectopen in new window

The text “Show advanced options” beside a green toggle which is turned on.
The text “Show advanced options” beside a green toggle which is turned on.

That switch is read-only and always on because that's what our constant binding says, but it's enough to get you moving for now – you can come back and replace it with a full @State property later.

These constant bindings come in all sorts of types: Booleans, strings, integers, and more are all available, and Swift will make sure you use the right one for each view type.

Similar solutions…
How to create custom bindings | SwiftUI by Example

How to create custom bindings
Two-way bindings in SwiftUI | SwiftUI by Example

Two-way bindings in SwiftUI
Bindings and forms | SwiftUI by Example

Bindings and forms
SwiftUI tips and tricks | SwiftUI by Example

SwiftUI tips and tricks
How to create a List or a ForEach from a binding | SwiftUI by Example

How to create a List or a ForEach from a binding

이찬희 (MarkiiimarK)
Never Stop Learning.