Group 组

SwiftUI提供一个Group群组视图,以对相似的内容进行分组。它主要有以下用途:

HStack{
	Group{
		CardView()
		CardView()
		CardView()
		CardView()
	}
	.frame(width:300)
}
// 例如:创建以下视图,每次点击该组时,都会在垂直和水平布局之间翻转,使用 Group 让我们可以将点击手势立即附加到所有内容

struct ContentView: View {
    @State private var layoutVertically = false
    var body: some View {
		    //Group 本身不影响布局
        Group {
            if layoutVertically {
                VStack {
                    UserView()
                }
            } else {
                HStack {
                    UserView()
                }
            }
        }
        .onTapGesture {
            layoutVertically.toggle()
        }
    }
}

GroupBox 组盒子

GroupBox 视图可以将视图分组在一起,并在它们后面放置浅色背景色。

1. 设置 GroupBox 标题

struct GroupBoxExample: View {
    
    @State private var userAgreed = false
    
    var body: some View {
        GroupBox(label:
            Label("Terms of Use", systemImage: "building.columns")
            .padding(.vertical)
        ) {
            ScrollView(.vertical, showsIndicators: true) {
                Text(agreementText)
                    .font(.footnote)
            }
            .frame(height: 250)
            Toggle(isOn: $userAgreed) {
                Text("I agree to the above terms")
            }
        }
        .padding()
    }
}

var agreementText = """
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
"""

2. GroupBox 会自动区分底色

GroupBox 的一个真正强大的功能是,如果您嵌套它们,它们会自动调整背景颜色,以便清楚地区分开内容

GroupBox("Your account") {
    Text("Outer Content")
    GroupBox {
        Text("Middle Content")
        GroupBox {
            Text("Inner Content")
        }
    }
}

在黑暗模式下这种效果即使不是最好,也很不错!另外虽然 GroupBox 在 macOS 上看起来不错,但在 iOS 上看起来一点也不好看。

how-to-group-views-visually-using-groupbox-3~dark@2x.webp

3. GroupBox 背景色设置

想要设置 的背景色,会发现 .background() 修饰符没有用,而需要使用 .backgroundStyle() 来代替。


.backgroundStyle(.cyan)

.backgroundStyle(.regularMaterial)

DisclosureGroup 可折叠组

// 状态属性:储存分组是否展开
@State private var settingsExpanded = true

Form{

	// 前面的Text是标题,后面是绑定状态参数
	DisclosureGroup("Audio Settings", isExpanded: $settingsExpanded) {                    
		Toggle("Toggle 1", isOn: $toggleStates.oneIsOn)
    Toggle("Toggle 2", isOn: $toggleStates.twoIsOn)

    // 可折叠组支持嵌套
    DisclosureGroup("Sub-items") {
        Text("Sub-item 1")
    } 
           
	}

}

OutlineGroup 折叠组

TBD