SwiftUI 基础之Toggle控件与@Binding属性装饰器(含代码demo)

本文深入解析SwiftUI中的Toggle控件与@Binding属性装饰器的使用技巧,通过一个控制列表数据显示的实例,展示了如何利用这两个特性实现数据状态的动态切换。适合初学者快速上手SwiftUI的数据绑定与交互设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
                }
            }
        }
    }
    
    
}

效果

41085-ad947c0caad34a9b.gif
Jietu20200118-212714.gif

更多SwiftUI教程和代码关注专栏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

知识大胖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值