SwiftUI 紀錄-排版

Zhi-Hong Lin
3 min readSep 2, 2024
  • HStack(水平)
  • VStack(垂直)
  • ZStack(重疊)
  • Spacer
  • GeometryReader
  • LazyVGrid/LazyHGrid

HStack(水平)

  • 用於將子 View 水平排列,並允許設定子 View 之間的間距 (spacing) 和垂直對齊方式 (alignment)。
HStack(spacing: 20) {
Image(systemName: "star.fill")
.foregroundColor(.yellow)
Text("Favorite")
Spacer()
}

VStack(垂直)

  • 用於將子 View 垂直排列,並可以設定間距 (spacing) 和水平方向的對齊方式 (alignment)。
VStack(alignment: .leading, spacing: 16) {
Text("Title")
.font(.title)
Text("Subtitle")
.font(.subheadline)
Text("Description goes here. This is a longer piece of text that will wrap to the next line.")
}

ZStack(重疊)

  • 用於將子 View 重疊排列,第一個子 View 位於最底層,後續的子 View 依次覆蓋在上。
ZStack {
Rectangle()
.fill(Color.blue)
.frame(width: 200, height: 200)
Text("Hello, World!")
.font(.title)
.foregroundColor(.white)
}

Spacer

  • 會無限延伸的一個 View,放在 Stack 外面會朝 XY 軸無限延伸。放在 Stack 裡面就會往 Stack 的主要方向延伸。可以透過 minLength 參數指定最小長度。
  • 常見用法是在 HStackVStack 中使用 Spacer 來將 View 推到兩側。
HStack {
Text("Left")
Spacer()
Text("Right")
}

GeometryReader

  • 根據父 View 的尺寸和位置,動態調整子 View 的大小和位置。
  • 提供了一個 GeometryProxy 對象,其中包含父 View 的各種屬性,如 sizeframesafeAreaInsets 等。
GeometryReader { geometry in
Text("Width: \\(geometry.size.width)")
.font(.title)
Text("Height: \\(geometry.size.height)")
.font(.title)
}

LazyVGrid/LazyHGrid

  • 用來建立垂直和水平的網格排版,只有當畫面需要渲染時才會載入相關的子 View,提升效能。
  • 可以指定每行有幾個 GridItem,並調整它們的大小和對齊方式。
LazyVGrid(columns: [
GridItem(.flexible()),
GridItem(.flexible())
]) {
ForEach(0..<20) { index in
Text("Item \\(index)")
.padding()
.background(Color.gray.opacity(0.3))
.cornerRadius(8)
}
}

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response