Bỏ qua để đến nội dung

👋 Giới thiệu SwiftUI

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).

// ❌ Imperative (UIKit)
let label = UILabel()
label.text = "Hello"
label.textColor = .blue
view.addSubview(label)
// ✅ Declarative (SwiftUI)
Text("Hello")
.foregroundColor(.blue)
Đặ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
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()
}

Mọi component UI trong SwiftUI đều conform protocol View:

protocol View {
associatedtype Body: View
@ViewBuilder var body: Self.Body { get }
}

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óc

Lư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ỉ text
#Preview {
ContentView()
}
// Multiple previews
#Preview("Light Mode") {
ContentView()
.preferredColorScheme(.light)
}
#Preview("Dark Mode") {
ContentView()
.preferredColorScheme(.dark)
}
SwiftUI UIKit
Text UILabel
Button UIButton
Image UIImageView
List UITableView
NavigationStack UINavigationController
@State Properties + reload

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

Tiếp theo, tìm hiểu về các View cơ bản trong SwiftUI.