SwiftUI提供一个Group群组视图,以对相似的内容进行分组。它主要有两个用途:
Group
视图通常用于解决 10 个子视图的限制:当 stack 里面子级元素超过 10 个时,可以用它来分组拆开Group
可以充当透明布局容器。这意味着它根本不会影响布局,但可以让我们根据需要添加 SwiftUI 修饰符,或者在不使用 @ViewBuilder
的情况下发回多个视图。当给 Group
视图添加修饰器的时候,修饰器就会应用到 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
视图可以将视图分组在一起,并在它们后面放置浅色背景色。如果需要,还可以选择添加标题。基本示例如下:
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.
"""
#Preview {
GroupBoxExample()
}
GroupBox
的一个真正强大的功能是,如果您嵌套它们,它们会自动调整颜色,以便清楚地区分它们
GroupBox("Your account") {
Text("Outer Content")
GroupBox {
Text("Middle Content")
GroupBox {
Text("Inner Content")
}
}
}
在黑暗模式下这种效果即使不是最好,也很不错!另外虽然 GroupBox
在 macOS 上看起来不错,但在 iOS 上看起来一点也不好看。
// 状态属性:储存分组是否展开
@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")
}
}
}
TBD