はじめに
@Binding の使い方
異なるView間で値を共有する方法として@Binding
を用いる
環境
SwiftUI
Xcode: 13.3.1
Code
@State
を用いて値を渡す場合
HomeView
struct HomeView: View {
@State var showNextPage = false
@State var button = false
var body: some View {
NavigationView{
VStack{
Text("Home page")
Button {
self.button.toggle()
} label: {
Text(self.button.description)
.foregroundColor(Color.white)
.padding()
}
.padding()
.background(self.button ? Color.blue : Color.red)
.cornerRadius(30)
NavigationLink("go next page", isActive: $showNextPage) {
NextPageView(button: $button)
}
}
}
}
}
NextPageView
struct NextPageView: View {
@State var button : Bool
init(button: Bool ){
self.button = button
}
var body: some View {
VStack{
Text("Next Page")
Button {
self.button.toggle()
} label: {
Text(self.button.description)
.foregroundColor(Color.white)
.padding()
}
.padding()
.background(self.button ? Color.blue : Color.red)
.cornerRadius(30)
}
}
}
HomeView -> NextPageView へは値が影響するが、
HomeView <- NextPageView へは値が影響しない。
@Binding
の場合
HomeView
struct HomeView: View {
@State var showNextPage = false
@State var button = false
var body: some View {
NavigationView{
VStack{
Text("Home page")
Button {
self.button.toggle()
} label: {
Text(self.button.description)
.foregroundColor(Color.white)
.padding()
}
.padding()
.background(self.button ? Color.blue : Color.red)
.cornerRadius(30)
NavigationLink("go next page", isActive: $showNextPage) {
NextPageView(button: $button)
}
}
}
}
}
NextPageView
struct NextPageView: View {
@Binding var button : Bool
init(button: Binding<Bool> = .constant(false) ){
_button = button
}
var body: some View {
VStack{
Text("Next Page")
Button {
self.button.toggle()
} label: {
Text(self.button.description)
.foregroundColor(Color.white)
.padding()
}
.padding()
.background(self.button ? Color.blue : Color.red)
.cornerRadius(30)
}
}
}
View間の値が互いに影響する。