Ios SwiftUI:在一个带间隔的VStack中均匀分布多个VStack
我试图构建一个包含多个VStack(元素)的VStack(容器),每个VStack(元素)都有一个标题和一个文本。元件VSTACK应均匀分布,并在两者之间有一个垫片 出于某种原因,它最多只能工作4个元素VStack,如果我增加,那么我将得到一个错误Ios SwiftUI:在一个带间隔的VStack中均匀分布多个VStack,ios,swiftui,vstack,Ios,Swiftui,Vstack,我试图构建一个包含多个VStack(元素)的VStack(容器),每个VStack(元素)都有一个标题和一个文本。元件VSTACK应均匀分布,并在两者之间有一个垫片 出于某种原因,它最多只能工作4个元素VStack,如果我增加,那么我将得到一个错误 Failed to build ContentView.swift Ambiguous reference to member 'buildingBlock()' 这是我的密码: import SwiftUI struct ContentView
Failed to build ContentView.swift
Ambiguous reference to member 'buildingBlock()'
这是我的密码:
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Spacer()
VStack {
Text("Title 1")
Text("Text 1")
}
Spacer()
VStack {
Text("Title 2")
Text("Text 2")
}
Spacer()
VStack {
Text("Title 3")
Text("Text 3")
}
Spacer()
VStack {
Text("Title 4")
Text("Text 4")
}
Spacer()
VStack {
Text("Title 5")
Text("Text 5")
}
Spacer()
VStack {
Text("Title 6")
Text("Text 6")
}
Spacer()
VStack {
Text("Title 7")
Text("Text 7")
}
Spacer()
VStack {
Text("Title 8")
Text("Text 8")
}
Spacer()
VStack {
Text("Title 9")
Text("Text 9")
}
Spacer()
VStack {
Text("Title 10")
Text("Text 10")
}
Spacer()'
}
.background(Color.red)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
由于SwiftUI的实现方式,一个视图最多只能有10个直接的、显式的子视图。您的顶级
VStack
有21个直接子视图:10个子VStack
s,以及它们周围的11个子s
有各种变通办法。如果确实需要硬编码的子视图列表,可以使用Group
使一些子视图成为间接的:
struct ContentView: View {
var body: some View {
VStack {
Group {
Spacer()
VStack {
Text("Title 1")
Text("Text 1")
}
Spacer()
VStack {
Text("Title 2")
Text("Text 2")
}
Spacer()
VStack {
Text("Title 3")
Text("Text 3")
}
}
Group {
Spacer()
VStack {
Text("Title 4")
Text("Text 4")
}
Spacer()
VStack {
Text("Title 5")
Text("Text 5")
}
Spacer()
VStack {
Text("Title 6")
Text("Text 6")
}
}
Group {
Spacer()
VStack {
Text("Title 7")
Text("Text 7")
}
Spacer()
VStack {
Text("Title 8")
Text("Text 8")
}
Spacer()
VStack {
Text("Title 9")
Text("Text 9")
}
}
Spacer()
VStack {
Text("Title 10")
Text("Text 10")
}
Spacer()
}
.background(Color.red)
}
}
在这里,顶级VStack
有6个直接子级:3个组
,2个间隔子
,1个VStack
。每个组
也有6个直接子代:3个VStack
和3个Spacer
。没有视图具有超过10个直接子视图
这里更好的方法是使用ForEach
生成子项:
struct ContentView: View {
var body: some View {
VStack {
Spacer()
ForEach(1 ... 10, id: \.self) { i in
Group {
VStack {
Text("Title \(i)")
Text("Text \(i)")
}
Spacer()
}
}
}
.background(Color.red)
}
}
现在,顶级的VStack
只有两个直接子视图:第一个Spacer
和ForEach
。ForEach
根据需要多次复制其子视图(组)
在本例中,我们使用组
来允许Swift推断ForEach
主体的类型,因为ForEach
主体将包含两条语句(VStack
和间隔符
),这将阻止Swift推断其类型。感谢您提供的详细且非常有趣的回复。你能补充一下为什么SwiftUI只允许10个直接子视图吗?我认为这很有限,我解释过了。搜索“理解”。请使用ForEach
pleeeease。