垂直排列视图
使用 VStack 将视图从上到下排列。
垂直排列视图 是 CoddyKit 上的免费 SwiftUI Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 SwiftUI Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 SwiftUI Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why You Need Stacks
A SwiftUI body can return only one view. To show several views together, you wrap them in a container that arranges them for you. 📦
Meet VStack
A VStack stacks its child views vertically, top to bottom. It is your go-to container for column-style layouts like a title above a subtitle.
Your First VStack
Place views inside the VStack braces and they appear in order, each on its own line. The first child sits at the top.
VStack {
Text("Hello")
Text("World")
}Order Matters
Children render in the exact order you write them. Swap two lines of code and the views swap places on screen. Top of the code is top of the column.
Centered by Default
By default a VStack centers its children horizontally and shrinks to fit its content, like a tidy little column hugging its views.
Mixing View Types
A VStack does not care what kind of views it holds. You can freely mix a Text, an Image, and a Button in the same vertical stack.
VStack {
Image(systemName: "star")
Text("Favorite")
}How Many Views Fit?
A stack can hold up to ten direct children at once. That is plenty for most screens, and you can always nest stacks for more.
Nesting Stacks
You can put a VStack inside another VStack to build richer layouts. Nesting lets you group related views so they move together.
VStack {
Text("Title")
VStack {
Text("Line 1")
Text("Line 2")
}
}Stacks Are Views Too
A VStack is itself a view, so you can apply modifiers like padding or background to the whole stack at once. The group acts as one unit.
Returning a VStack from body
Since body needs a single view, returning a VStack is the classic way to show many views. The stack becomes that one returned view.
var body: some View {
VStack {
Text("One")
Text("Two")
}
}When to Reach for VStack
Use a VStack whenever items should read top to bottom: a heading over body text, a label over a value, or a form laid out in rows.
Quick Check
Let's make sure VStack ordering is clear.
Recap: Vertical Stacking
Nice work! A VStack arranges views top to bottom in code order, centers them by default, and acts as one view you can style or nest. 🎉
常见问题解答
「垂直排列视图」课时是免费的吗?
是的 — 「垂直排列视图」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 SwiftUI Academy 课程的其余内容,请升级到 CoddyKit PRO。 SwiftUI Academy 课程共包含 4 节课。
「垂直排列视图」这节课中我会学到什么?
使用 VStack 将视图从上到下排列。 你通过在浏览器中直接运行的动手代码来练习 SwiftUI Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 SwiftUI Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 SwiftUI Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「垂直排列视图」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 SwiftUI Academy 课中编写并运行代码吗?
能。每节 SwiftUI Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。