-
@Binding
的作用是在保存状态的属性和更改数据的视图之间创建双向连接,将当前属性连接到存储在别处的单一数据源(single source of truth)
,而不是直接存储数据。将存储在别处的值语意的属性转换为引用语义,在使用时需要在变量名加$
符号。 -
通常使用场景是把当前
View
中的@State
值类型传递给其子View
,如果直接传递@State
值类型,将会把值类型复制一份copy
,那么如果子View
中对值类型的某个属性进行修改,父View
不会得到变化,所以需要把@State
转成@Binding
传递。 -
@Binding
修饰属性无需有初始化值,Binding
可以配合@State
或ObservableObject
对象中的值属性一起使用,注意不是@ObservedObject
属性包装器。
import SwiftUI
struct Product: Identifiable {
var id = UUID()
var isFavorited: Bool
var title: String
}
struct FilterView: View {
@Binding var showFavorited: Bool
var body: some View {
Toggle(isOn: $showFavorited, label: {
Text("Change filter")
})
}
}
struct ProductsView: View {
let products: [Product] = [
Product(isFavorited: true, title: "Lily"),
Product(isFavorited: false, title: "Andy")
]
@State private var showFavorited: Bool = false
var body: some View {
Form{
Section(content: {
FilterView(showFavorited: $showFavorited)
})
Section(content: {
ForEach(products){product in
if !self.showFavorited || product.isFavorited {
Text(product.title)
}
}
})
}
}
}
struct ProductsView_Previews: PreviewProvider {
static var previews: some View {
ProductsView()
}
}