SwiftUI 基础之Toggle控件与@Binding属性装饰器(含代码demo)
Toggle 介绍
A control that toggles between on and off states.
在打开和关闭状态之间切换的控件
大白话:状态开关
@Binding 属性装饰器
A manager for a value that provides a way to mutate it.
值的管理器,提供了一种对其进行变异的方法
大白话:将一个变量从不可以修改,转化为可以修改。而且是可以跨视图修改。就是将变量的引用传给其他的视图
Toggle和@Binding联合demo
我们做一个开关来控制列表中数据的显示
import SwiftUI
struct Product : Identifiable{
let id = UUID()
let title:String
let isFavorited:Bool
}
struct FilterView: View {
@Binding var showFavorited: Bool
var body: some View {
Toggle(isOn: $showFavorited) {
Text("Change filter")
}
}
}
struct ContentView: View {
let products: [Product] = [
Product(title:"abc1",isFavorited: true),
Product(title:"abc2",isFavorited: true),
Product(title:"abc3 false",isFavorited: false),
Product(title:"abc4",isFavorited: true),
]
@State private var showFavorited: Bool = false
var body: some View {
List {
FilterView(showFavorited: $showFavorited)
ForEach(products) { product in
if !self.showFavorited || product.isFavorited {
Text(product.title)
}
}
}
}
}
效果
更多SwiftUI教程和代码关注专栏
- 请关注我的专栏 SwiftUI教程与源码