Giới thiệu SwiftUI
SwiftUI là gì?
SwiftUI là framework declarative UI của Apple, ra mắt năm 2019, cho phép xây dựng giao diện trên tất cả nền tảng Apple (iOS, macOS, watchOS, tvOS).
Declarative vs Imperative
// ❌ Imperative (UIKit)
let label = UILabel()
label.text = "Hello"
label.textColor = .blue
view.addSubview(label)
// ✅ Declarative (SwiftUI)
Text("Hello")
.foregroundColor(.blue)Ưu điểm của SwiftUI
| Đặc điểm | Mô tả |
|---|---|
| Declarative | Mô tả UI muốn có, không phải cách tạo |
| Live Preview | Xem thay đổi real-time trong Xcode |
| Cross-platform | Một codebase cho iOS, macOS, watchOS |
| Modern Swift | Tận dụng các tính năng mới của Swift |
| Less Code | Ít code hơn so với UIKit |
Cấu trúc cơ bản
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Text("Hello, SwiftUI!")
.font(.largeTitle)
.foregroundColor(.blue)
Button("Tap Me") {
print("Button tapped!")
}
.padding()
.background(.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
}
}
#Preview {
ContentView()
}View Protocol
Mọi component UI trong SwiftUI đều conform protocol View:
protocol View {
associatedtype Body: View
@ViewBuilder var body: Self.Body { get }
}Modifiers
Modifiers thay đổi appearance và behavior của views:
Text("Hello")
.font(.title) // Font
.foregroundColor(.red) // Màu chữ
.padding() // Padding
.background(.yellow) // Background
.cornerRadius(8) // Bo gócLưu ý: Thứ tự modifiers quan trọng!
// Khác nhau:
Text("A").padding().background(.red) // Background bao padding
Text("B").background(.red).padding() // Background chỉ textPreview với Canvas
#Preview {
ContentView()
}
// Multiple previews
#Preview("Light Mode") {
ContentView()
.preferredColorScheme(.light)
}
#Preview("Dark Mode") {
ContentView()
.preferredColorScheme(.dark)
}So sánh với UIKit
| SwiftUI | UIKit |
|---|---|
Text | UILabel |
Button | UIButton |
Image | UIImageView |
List | UITableView |
NavigationStack | UINavigationController |
@State | Properties + reload |
Khi nào dùng SwiftUI?
✅ Nên dùng:
- Dự án mới
- iOS 15+
- Prototype nhanh
- Ứng dụng đơn giản đến trung bình
⚠️ Cân nhắc:
- Cần hỗ trợ iOS < 15
- Tích hợp nhiều UIKit code
- Complex custom animations
Bước tiếp theo
Tiếp theo, tìm hiểu về các View cơ bản trong SwiftUI.
Last updated on