昨天我們學會了SwiftUI 的 Layout ,知道如何透過Stack、Spacer、Alignment、Frame來控制畫面。
今天,我們要來看看 SwiftUI 中最常使用的UI 元件 (Views)。這些元件是日常開發 App 時不可或缺的工具。
Text
是最基本的元件,用來顯示文字。
Text("Hello, SwiftUI!")
.font(.title)
.foregroundColor(.blue)
常見修飾符:
.font(.title)
:字體大小.foregroundColor(.red)
:文字顏色.bold()
:粗體.italic()
:斜體Image
可以載入系統圖示(SF Symbols)或 App 內的圖片資源。
VStack {
Image(systemName: "star.fill") // 系統內建圖示
.foregroundColor(.yellow)
.font(.largeTitle)
Image("anon") // 專案資源內的圖片
.resizable()
.scaledToFit()
.frame(width: 200, height: 200)
}
常見修飾符:
.resizable()
:圖片可縮放.scaledToFit()
:保持比例縮放.frame(width,height)
:設定大小Button
是互動元件,常用來觸發動作。
Button("點我一下") {
showAlert = true
}.alert("按鈕被點擊!", isPresented: $showAlert, actions: {})
也可以自訂樣式:
Button(action: {
print("自訂按鈕")
}) {
HStack {
Image(systemName: "paperplane.fill")
Text("送出")
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
用來輸入文字內容,通常會搭配 @State
來儲存使用者輸入。
(@State
我們之後會詳細介紹)
@State private var name: String = ""
var body: some View {
VStack {
TextField("請輸入姓名", text: $name)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Text("Hello, \(name)")
}
}
用來切換 開 / 關 狀態。
@State private var isOn = false
var body: some View {
Toggle("啟用通知", isOn: $isOn)
.padding()
}
用來顯示一組資料。
let items = ["代辦事項 1", "代辦事項 2", "代辦事項 3"]
var body: some View {
List(items, id: \.self) { item in
Text(item)
}
}
也能支援 動態內容 + 多種元素:
List {
Section(header: Text("水果")) {
Text("蘋果")
Text("香蕉")
}
Section(header: Text("飲料")) {
Text("咖啡")
Text("奶茶")
}
}
用來顯示進度或等待狀態。
VStack {
ProgressView("載入中...") // 無限轉圈
ProgressView(value: 0.5) // 50% 進度條
}.padding()
今天我們介紹了 SwiftUI 的常見 UI 元件:
這些元件是 SwiftUI 開發的基礎,你可以靈活組合,打造屬於自己的 App 介面。
明天,我們將進一步介紹 互動與彈出元件 (如 Alert、Sheet),讓 App 更加生動。