各種對齊 (alignment)
Last updated
Was this helpful?
Last updated
Was this helpful?
HStack, VStack, .frame( ) 等等,都有自己的 alignment,但它們都只是管理自己內部的對齊而已 ...
import SwiftUI
import PlaygroundSupport
let bg = Color(white: 0.3).opacity(0.3)
let spacer = Spacer().frame(width: 2).background(Color.orange)
// ⭐️ 指定「靠右對齊」
let vstack = VStack(alignment: .trailing) {
spacer
Text("Hello")
Text("World")
}.background(bg).padding(10)
// live view
struct ContentView: View {
var body: some View {
VStack(spacing: 10) {
// ⭐️ 這個指定「靠右對齊」,似乎沒有問題。
vstack.border(Color.black)
// ⚠️ 這個把寬度加寬,「靠右對齊」似乎就有問題了?
// 這個主要的問題是:VStack 只對內部的物件做對齊,
// 所以內部物件(Spacer, Text)依然是靠右對齊。
// ⭐️ 一旦我們用 .frame(width:) 將 VStack 加寬後,
// VStack 馬上變成 .frame 的子物件,如果我們
// 不指定 .frame 的對齊方式的話,預設還是會將整個
// VStack 「置中對齊」‼️
vstack
.frame(width: 200)
.border(Color.black)
// ⭐️ 所以正確的做法是:
// 1. VStack 本身要指定「靠右對齊」之外
// 2. frame(width:) 也要指定「靠右對齊」
vstack
.frame(width: 350, alignment: .trailing)
.border(Color.black)
}// container: VStack
.padding(10)
.frame(maxWidth: .infinity)
.frame(height: 300)
.border(Color.black)
.shadow(radius: 8)
.padding()
.background(Color.gray)
.cornerRadius(10)
}
}
PlaygroundPage.current.setLiveView(ContentView())
- Hacking with Swift