SwiftUI 4.0为Toggle视图在iOS 16中增加属性多选功能

Posted 大熊猫侯佩

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SwiftUI 4.0为Toggle视图在iOS 16中增加属性多选功能相关的知识,希望对你有一定的参考价值。

概览

Toggle是SwiftUI中我们最常用的视图之一,我们用它来启用和禁用某些属性的值。

在SwiftUI 4.0中,Apple为Toggle增加了属性多选的支持,我们不仅支持单个属性的设置,同样支持多个属性值的同时设置:

如上图所示:不管上方有多少单个选项存在,在ios 16中实现下方的Enable All 选项只需一行代码!

废话少叙,Let’s do it! 😉


SwiftUI 4.0 中的实现

在SwiftUI 4.0中,Toggle视图增加了一个新的多选构造器,用它我们可以轻松实现属性多选的功能:

注意其中最后一个参数,它是KeyPath类型,并且需要键对应值的类型为Binding<Bool>,这意味着我们必须为中间的sources参数传递数组的绑定:

struct Item: Identifiable 
    let id: String
    var enable = false


@State var items = [
    Item(id: "Super Power"),
    Item(id: "Speed Fast"),
    Item(id: "Immortality"),
]

Toggle("Enable All", sources: $items, isOn: \\.enable)

我们甚至可以有条件的选择部分属性:

struct Item: Identifiable 
    let id: String
    var value: Int
    var enable = false


@State var items = [
    Item(id: "Super Power", value: 5),
    Item(id: "Speed Fast", value: 3),
    Item(id: "Immortality", value: 5),
    Item(id: "Transparency", value: 2),
    Item(id: "Something like Ant-Man", value: 4)
]

Toggle("Enable All", sources: $items.filter $0.wrappedValue.value > 3, isOn: \\.enable)

执行效果如下图所示:

现在,我们在iOS16中想要实现全部或部分属性的启用或禁用功能,只需一行代码了,棒棒哒💯

全部源代码

注意,下面的代码需要在Xcode 14beta中编译运行:

import SwiftUI
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

struct Item: Identifiable 
    let id: String
    var value: Int
    var enable = false


struct MainView: View 
    
    @State var items = [
        Item(id: "Super Power", value: 5),
        Item(id: "Speed Fast", value: 3),
        Item(id: "Immortality", value: 5),
        Item(id: "Transparency", value: 2),
        Item(id: "Something like Ant-Man", value: 4)
    ]
    
    var body: some View 
        NavigationStack 
            Form 
                Section(content: 
                    ForEach($items)  $item in
                        Toggle(item.id, isOn: $item.enable)
                            .foregroundColor(item.enable ? .green : .gray)
                            .font(item.enable ? .headline : .subheadline)
                            .animation(.interactiveSpring(), value: item.enable)
                    
                , header: 
                    Text("Abilities")
                )
                
                
                Section(content: 
                    Toggle("Enable All", sources: $items.filter $0.wrappedValue.value > 3, isOn: \\.enable)
                , header: 
                    Text("Select All!")
                )
            
            .navigationTitle("Hero Abilities Setup")
        
    


PlaygroundPage.current.liveView = UIHostingController(rootView: MainView())

总结

在本篇博文中,我们介绍了SwiftUI 4.0中Toggle的多选功能,这样在iOS 16中可以大幅度精简原先的代码了,nice!

感谢观赏,再会 😎

以上是关于SwiftUI 4.0为Toggle视图在iOS 16中增加属性多选功能的主要内容,如果未能解决你的问题,请参考以下文章