The Util Designer
SwiftUI HStack佈局
xcode 13.3.1, swift 5.5, iOS 15.4
2022-08-11
SwiftUI 提供了三個佈局元件,比如HStack、VStack和ZStack,這次主要介紹HStack佈局。
1. HStack佈局會把每個子元件水平的排開。
import SwiftUI

struct HStackExample: View {
    var body: some View {
        HStack {
            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)
            Text("Cat")
            Image(systemName: "car.fill")
                .resizable()
                .scaledToFit()
                .foregroundColor(.blue)
        }
    }
}
從上圖所看,每個HStack的子元件都以中間線為基準來佈局。
HStack提供了幾個基準來佈局包括:top、center、bottom、firstTextBaseline和lastTextBaseline。
2. 現在使用top alignment來佈局,程式如下。
import SwiftUI

struct HStackExample: View {
    var body: some View {
        HStack(alignment: .top) {
            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)
            Text("Cat")
            Image(systemName: "car.fill")
                .resizable()
                .scaledToFit()
                .foregroundColor(.blue)
        }
    }
}
3. 只要修改HStack的alignemnt參數,去改變其基準的佈局就可以,下面把這5種基準都都列出來方便做對比。
top
center
bottom
firstTextBaseline
lastTextBaseline