@Binding
@Binding
은 부모 View의 @State와 같은 값 연결 시켜준다.
예제 소스
import SwiftUI
struct ParentsView: View {
@State private var isOn = false
var body: some View {
VStack {
Toggle("On / Off", isOn: $isOn)
ChildView(isOn: $isOn)
}
}
}
struct ChildView: View {
@Binding var isOn: Bool
var imageName: String {
if isOn {
return "lightbulb.fill"
} else {
return "lightbulb"
}
}
var imageColor: Color {
if isOn {
return Color.yellow
} else {
return Color.black
}
}
var body: some View {
Image(systemName: imageName)
.resizable()
.frame(width: 50, height: 50, alignment: .center)
.foregroundColor(imageColor)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
Group {
ParentsView()
}
}
}