容器组件
- 布局容器本身也是
View,可互相嵌套 - 容器内子视图按主轴方向依次排列,支持设置间距、对齐
- 修饰符作用范围:写在容器上 → 作用所有子视图;写在单个视图上 → 仅作用自身
VStack
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(alignment: .trailing, spacing: 10) {
Text("hello").background(.green)
Text("world")
// 必须颜色占位
Color.clear.frame(height: 10)
}
.frame(width: 100, height: 80)
.background(.red)
}
}
#Preview {
ContentView()
}
HStack
// 语法
HStack(alignment: 对齐方式, spacing: 间距) {
子视图
}
import SwiftUI
struct ContentView: View {
var body: some View {
HStack(alignment: .top) {
Text("hello").background(.red)
Text("world").background(.red)
Text("!").background(.red)
Text("ahusi").frame(width: 100,height: 100).background(.red)
}.background(.green).frame(width: 1000, height: 100)
}
}
#Preview {
ContentView()
}
ZStack
ZStack = Z 轴堆叠,视图上下层叠显示(后写的视图覆盖在先写的视图之上),适合做背景、浮窗、角标。
- 对齐控制所有子视图的相对位置:
.center/.top/.bottom/.leading/.trailing/.topLeading等
ZStack(alignment: 对齐方式) {
// 底层视图
// 上层视图(覆盖底层)
}
import SwiftUI
struct ContentView: View {
var body: some View {
ZStack {
// 底层:红色背景块
Color.red
.frame(width: 200, height: 120)
.cornerRadius(12)
// 上层:白色文字
Text("层叠布局")
.font(.title)
.foregroundColor(.white)
}
}
}
#Preview {
ContentView()
}
Spacer
import SwiftUI
struct ContentView: View {
var body: some View {
HStack{
Text("左侧内容")
Spacer()
Text("右侧内容")
}
}
}
#Preview {
ContentView()
}
Divider 分割线
import SwiftUI
struct ContentView: View {
var body: some View {
VStack(spacing: 10) {
Text("选项1")
Divider() // 分割线
Text("选项2")
Divider()
Text("选项3")
}
.padding()
}
}
#Preview {
ContentView()
}