在 Swift 5.2 和 iOS 13.4 中,根据您的需要,您可以使用以下示例之一来调整您VStack
的顶级领先约束和全尺寸框架。
请注意,下面的代码片段都导致相同的显示,但不保证在调试视图层次结构时可能出现的有效框架VStack
或元素数量。View
一、使用frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)
方法
最简单的方法是设置VStack
最大宽度和高度的框架,并在以下位置传递所需的对齐方式frame(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)
:
struct ContentView: View {
var body: some View {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
.frame(
maxWidth: .infinity,
maxHeight: .infinity,
alignment: .topLeading
)
.background(Color.red)
}
}
2.使用Spacer
s强制对齐
您可以将您的VStack
inside 嵌入一个完整尺寸HStack
并使用 trailing 和 bottom Spacer
s 来强制您的VStack
顶部前导对齐:
struct ContentView: View {
var body: some View {
HStack {
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
Spacer() // VStack bottom spacer
}
Spacer() // HStack trailing spacer
}
.frame(
maxWidth: .infinity,
maxHeight: .infinity
)
.background(Color.red)
}
}
3. 使用ZStack
全尺寸背景View
此示例显示如何将您嵌入VStack
到ZStack
具有顶部前导对齐的内部。请注意Color
视图如何用于设置最大宽度和高度:
struct ContentView: View {
var body: some View {
ZStack(alignment: .topLeading) {
Color.red
.frame(maxWidth: .infinity, maxHeight: .infinity)
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
}
}
}
4.使用GeometryReader
GeometryReader
有以下声明:
将其内容定义为自身大小和坐标空间的函数的容器视图。[...] 这个视图返回一个灵活的首选大小到它的父布局。
下面的代码片段显示了如何使用顶级领先约束和全尺寸框架GeometryReader
对齐您的:VStack
struct ContentView : View {
var body: some View {
GeometryReader { geometryProxy in
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
}
.frame(
width: geometryProxy.size.width,
height: geometryProxy.size.height,
alignment: .topLeading
)
}
.background(Color.red)
}
}
五、使用overlay(_:alignment:)
方法
如果你想VStack
在现有的 full size 上对齐你的顶级领先约束View
,你可以使用overlay(_:alignment:)
方法:
struct ContentView: View {
var body: some View {
Color.red
.frame(
maxWidth: .infinity,
maxHeight: .infinity
)
.overlay(
VStack(alignment: .leading) {
Text("Title")
.font(.title)
Text("Content")
.font(.body)
},
alignment: .topLeading
)
}
}
展示: