Skip to Content
iOS👋 Giới thiệu SwiftUI

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ểmMô tả
DeclarativeMô tả UI muốn có, không phải cách tạo
Live PreviewXem thay đổi real-time trong Xcode
Cross-platformMột codebase cho iOS, macOS, watchOS
Modern SwiftTậ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ó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 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

SwiftUIUIKit
TextUILabel
ButtonUIButton
ImageUIImageView
ListUITableView
NavigationStackUINavigationController
@StateProperties + 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