The Util Designer
SwiftUI VStack佈局
xcode 13.4.1, swift 5.5, iOS 15.4
2022-08-11
SwiftUI 提供了三個佈局元件,比如HStack、VStack和ZStack,這次主要介紹VStack佈局。
1. VStack佈局會把每個子元件垂直的排開。
struct VStackExample: View {
    var body: some View {
        VStack {
                Image(systemName: "network")
                    .resizable()
                    .scaledToFit()
                    .frame(width: 100)
                    .foregroundColor(.orange)
                Text("""
Tenali Raman was once walking along a
forest path when he was stopped by a merchant.
“I’m looking for my camel which has strayed away.
Did you see it passing by?” asked the merchant.
""")
                    .multilineTextAlignment(.center)
                Image(systemName: "car.fill")
                    .resizable()
                    .scaledToFit()
                    .foregroundColor(.blue)
            }
        }
}
從上圖所看,每個VStack的子元件都以中間線為基準來佈局。
VStack提供了幾個基準來佈局包括:leading、center、trailing。
2. 現在使用 leading alignment來佈局,程式如下。
import SwiftUI

struct VStackExample: View {
    var body: some View {
        VStack(alignment: .leading) {
                Image(systemName: "network")
                    .resizable()
                    .scaledToFit()
                    .frame(width: 100)
                    .foregroundColor(.orange)
                Text("""
Tenali Raman was once walking along a
forest path when he was stopped by a merchant.
“I’m looking for my camel which has strayed away.
Did you see it passing by?” asked the merchant.
""")
                    .multilineTextAlignment(.center)
                Image(systemName: "car.fill")
                    .resizable()
                    .scaledToFit()
                    .foregroundColor(.blue)
            }
        }
}
3. 只要修改VStack的alignemnt參數,去改變其基準的佈局就可以,下面把這3種基準都都列出來方便做對比。
leading
center
trailing