When you work with multiple components and need to synchronize the states, you'll need to use Binding. In this tutorial, I'll show you how to bind the states and set a default value for a Preview.
How to synchronize states across multiple views and set the constant for your preview
Binding States
- Use @Binding to synchronize the states between two views.
- When the NewView is referenced, pass the state as a Binding, with $.
struct ContentView: View {
@State var show = false
var body: some View {
NewView(show: $show)
}
}
struct NewView: View {
@Binding var show: Bool
}
..
Default Constant for Preview
When you set the Binding with only a value type, you'll need to set a default for the Preview to work. With Binding, you can use the .constant(true).
NewView(show: .constant(true))
..
Final Layout
In this example, we have 2 views that need to sync the show states. Like this, we can toggle using the tap gesture separately in their respective file.
struct ContentView: View {
@State var show = false
var body: some View {
ZStack {
Text("View Transition")
.padding()
.background(Capsule().stroke())
.onTapGesture {
withAnimation(.spring()) {
show.toggle()
}
}
if show {
NewView(show: $show)
.transition(.move(edge: .bottom))
.zIndex(1)
}
}
}
}
..
NewView.swift is where you set the Binding, which is synchronized with the ContentView's show state.
struct NewView: View {
@Binding var show: Bool
var body: some View {
RoundedRectangle(cornerRadius: 30)
.fill(Color.blue)
.padding()
.onTapGesture {
withAnimation(.spring()) {
show.toggle()
}
}
}
}
struct NewView_Previews: PreviewProvider {
static var previews: some View {
NewView(show: .constant(true))
}
}
..