介绍
SwiftUI 提供了三種不同类型的堆叠,以在不同方向上结合视图。根据你如何去排列视图,而可以使用:
- HStack - 水平排列。
- VStack - 垂直排列。
- ZStack - 一个图层重叠在其他图层之上
VStack
垂直排列所有控件
// 自定义左对齐 间距20
// VStack(alignment: .leading, spacing: 20) {
VStack {
Text("SwiftUI")
.font(.system(size: 40 ,design: .rounded))
.fontWeight(.medium)
.foregroundColor(.black)
.frame(width: 200)
Image("jr9Li_iNaE0")
.resizable()
.scaledToFit()
Text("SwiftUI")
.font(.system(size: 40 ,design: .rounded))
.fontWeight(.medium)
.foregroundColor(.black)
.frame(width: 200)
}
HStack
用法和VStack 类似
struct product:View {
var title: String
var price: String
var body: some View {
VStack(alignment: .center, spacing: 20) {
Text(title)
.font(.system(size: 30 ,design: .rounded))
.fontWeight(.medium)
.foregroundColor(.white)
Text(price)
.font(.system(size: 50 ,design: .rounded))
.fontWeight(.medium)
.foregroundColor(.white)
Text("per month")
.font(.system(size: 20 ,design: .rounded))
.fontWeight(.medium)
.foregroundColor(.white)
}
.padding(40)
.background(Color.purple)
.cornerRadius(10)
}
}
struct ContentView: View {
var body: some View {
HStack{
product(title:"Base",price:"$25")
product(title:"SwiftUI",price:"$50")
}
}
}
ZStack
Z轴排布视图
HStack{
product(title:"Base",price:"$25")
ZStack{
product(title:"SwiftUI",price:"$50")
Text("Best for designer")
.font(.system(.caption, design: .rounded))
.fontWeight(.bold)
.foregroundColor(.white)
.padding(5)
.background(Color(red: 255/255, green: 183/255, blue: 37/255))
.offset(x:0,y:87)
}
}