Binding的学习与使用

  • @Binding的作用是在保存状态的属性和更改数据的视图之间创建双向连接,将当前属性连接到存储在别处的单一数据源(single source of truth),而不是直接存储数据。将存储在别处的值语意的属性转换为引用语义,在使用时需要在变量名加$符号。

  • 通常使用场景是把当前View中的@State值类型传递给其子View,如果直接传递@State值类型,将会把值类型复制一份copy,那么如果子View中对值类型的某个属性进行修改,父View不会得到变化,所以需要把@State转成@Binding传递。

  • @Binding 修饰属性无需有初始化值,Binding可以配合@StateObservableObject对象中的值属性一起使用,注意不是@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()
    }
}

在这里插入图片描述
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值