swiftUI 子视图修改父视图的属性

本文详细展示了如何在SwiftUI中利用`@State`和`@Binding`实现子视图对父视图属性的实时更新。
摘要由CSDN通过智能技术生成

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

  • 8
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值