swiftUI 子视图修改父视图的属性
swiftUI中的子视图可以通过 @Binging 关键字去修改父视图的值,具体怎么去使用直接上代码:
import SwiftUI
struct BindingBootCamp: View {
@State var bgColor: Color = .yellow
@State var title = "background title"
var body: some View {
ZStack{
bgColor.ignoresSafeArea()
VStack{
Text(title.uppercased())
.font(.title)
.foregroundColor(.white)
MyButton(fatherBgColor: $bgColor, fatherBgTitle: $title)
}
}
}
}
#Preview {
BindingBootCamp()
}
/// 子视图修改父视图属性
struct MyButton: View {
@Binding var fatherBgColor: Color
@State var hadClick = false
@Binding var fatherBgTitle: String
var body: some View {
Button("Button") {
fatherBgColor = self.hadClick ? .yellow : .gray
fatherBgTitle = self.hadClick ? "background title" : "background title had change"
hadClick = !hadClick
} .foregroundColor(.white)
.padding()
.padding(.horizontal, 20)
.background(Color.red)
.cornerRadius(10)
}
}
子视图中通过@Binding创建对应关键字,然后在创建实例的时候,父视图通过 $ 关键字符把对应属性地址传递给子视图,然后子视图修改自身对象时候直接修改父视图的对应属性的值。
效果如下:
录屏2024-03-12 17.59.11