@Binding and @State
August 30, 2025•1,629 words
SwiftUI @State and @Binding Guide for iOS Developers
@State Property Wrapper
English:
@State is a property wrapper that allows you to create mutable state within a SwiftUI view. It's designed for simple value types (like String, Int, Bool) that are owned and managed by the view itself. When a @State property changes, SwiftUI automatically re-renders the view to reflect the new state.
Key characteristics:
Used for local state management within a single view
Should be private to the view that owns it
Automatically triggers view updates when the value changes
Best for simple value types
Vietnamese:
@State là một property wrapper cho phép bạn tạo trạng thái có thể thay đổi trong một SwiftUI view. Nó được thiết kế cho các kiểu giá trị đơn giản (như String, Int, Bool) được sở hữu và quản lý bởi chính view đó. Khi một thuộc tính @State thay đổi, SwiftUI tự động render lại view để phản ánh trạng thái mới.
Đặc điểm chính:
Được sử dụng để quản lý trạng thái cục bộ trong một view duy nhất
Nên được khai báo private cho view sở hữu nó
Tự động kích hoạt cập nhật view khi giá trị thay đổi
Tốt nhất cho các kiểu giá trị đơn giản
Example Code:
import SwiftUI
struct CounterView: View {
@State private var count: Int = 0
@State private var isShowingAlert: Bool = false
@State private var userName: String = ""
var body: some View {
VStack(spacing: 20) {
Text("Count: \(count)")
.font(.title)
HStack {
Button("Decrease") {
count -= 1
}
.disabled(count <= 0)
Button("Increase") {
count += 1
}
}
TextField("Enter your name", text: $userName)
.textFieldStyle(RoundedBorderTextFieldStyle())
.padding()
Button("Show Alert") {
isShowingAlert = true
}
}
.alert("Hello \(userName.isEmpty ? "User" : userName)!", isPresented: $isShowingAlert) {
Button("OK") { }
}
}
}
@Binding Property Wrapper
English:
@Binding creates a two-way connection between a child view and its parent view's state. It doesn't own the data but provides a way to read and write a value that's owned by another view. This is essential for passing data between parent and child views while maintaining a single source of truth.
Key characteristics:
Creates a two-way data connection between views
Doesn't own the state, just references it
Allows child views to modify parent view's state
Uses
$syntax to pass binding from parent to child
Vietnamese:
@Binding tạo ra một kết nối hai chiều giữa view con và trạng thái của view cha. Nó không sở hữu dữ liệu mà cung cấp cách để đọc và ghi một giá trị được sở hữu bởi view khác. Điều này rất quan trọng để truyền dữ liệu giữa các view cha và con trong khi duy trì một nguồn sự thật duy nhất.
Đặc điểm chính:
Tạo kết nối dữ liệu hai chiều giữa các view
Không sở hữu trạng thái, chỉ tham chiếu đến nó
Cho phép view con sửa đổi trạng thái của view cha
Sử dụng cú pháp
$để truyền binding từ cha xuống con
Example Code:
import SwiftUI
// Parent View
struct ParentView: View {
@State private var isToggleOn: Bool = false
@State private var sliderValue: Double = 50.0
@State private var selectedColor: Color = .blue
var body: some View {
VStack(spacing: 30) {
Text("Parent View Controls")
.font(.title)
.foregroundColor(selectedColor)
// Pass bindings to child views using $ syntax
ToggleChildView(isOn: $isToggleOn)
SliderChildView(value: $sliderValue)
ColorPickerChildView(selectedColor: $selectedColor)
// Display current values in parent
VStack {
Text("Current Values:")
.font(.headline)
Text("Toggle: \(isToggleOn ? "ON" : "OFF")")
Text("Slider: \(String(format: "%.1f", sliderValue))")
Rectangle()
.fill(selectedColor)
.frame(width: 100, height: 50)
.cornerRadius(8)
}
}
.padding()
}
}
// Child View 1: Toggle
struct ToggleChildView: View {
@Binding var isOn: Bool
var body: some View {
VStack {
Text("Child Toggle View")
.font(.headline)
Toggle("Enable Feature", isOn: $isOn)
.padding()
}
.background(Color.gray.opacity(0.1))
.cornerRadius(10)
}
}
// Child View 2: Slider
struct SliderChildView: View {
@Binding var value: Double
var body: some View {
VStack {
Text("Child Slider View")
.font(.headline)
Slider(value: $value, in: 0...100) {
Text("Value")
}
.padding()
}
.background(Color.gray.opacity(0.1))
.cornerRadius(10)
}
}
// Child View 3: Color Picker
struct ColorPickerChildView: View {
@Binding var selectedColor: Color
var body: some View {
VStack {
Text("Child Color Picker View")
.font(.headline)
ColorPicker("Choose Color", selection: $selectedColor)
.padding()
}
.background(Color.gray.opacity(0.1))
.cornerRadius(10)
}
}
Advanced Example: Complete App
English:
Here's a more complex example that demonstrates both @State and @Binding working together in a practical shopping cart scenario. This shows how data flows between multiple views and maintains consistency.
Vietnamese:
Đây là một ví dụ phức tạp hơn minh họa cả @State và @Binding làm việc cùng nhau trong một kịch bản giỏ hàng thực tế. Điều này cho thấy cách dữ liệu chảy giữa nhiều view và duy trì tính nhất quán.
import SwiftUI
// Data Models
struct Product: Identifiable {
let id = UUID()
let name: String
let price: Double
}
struct CartItem: Identifiable {
let id = UUID()
let product: Product
var quantity: Int
}
// Main App View
struct ShoppingAppView: View {
@State private var cartItems: [CartItem] = []
@State private var isShowingCart: Bool = false
let availableProducts = [
Product(name: "iPhone 15", price: 999.0),
Product(name: "MacBook Pro", price: 1999.0),
Product(name: "AirPods Pro", price: 249.0),
Product(name: "Apple Watch", price: 399.0)
]
var body: some View {
NavigationView {
VStack {
Text("Shopping App")
.font(.largeTitle)
.padding()
ProductListView(
products: availableProducts,
cartItems: $cartItems
)
Spacer()
Button("View Cart (\(cartItems.count) items)") {
isShowingCart = true
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
.sheet(isPresented: $isShowingCart) {
CartView(cartItems: $cartItems)
}
}
}
}
// Product List View
struct ProductListView: View {
let products: [Product]
@Binding var cartItems: [CartItem]
var body: some View {
List(products) { product in
ProductRowView(
product: product,
cartItems: $cartItems
)
}
}
}
// Product Row View
struct ProductRowView: View {
let product: Product
@Binding var cartItems: [CartItem]
@State private var quantity: Int = 1
var body: some View {
HStack {
VStack(alignment: .leading) {
Text(product.name)
.font(.headline)
Text("$\(String(format: "%.2f", product.price))")
.foregroundColor(.secondary)
}
Spacer()
Stepper("Quantity: \(quantity)", value: $quantity, in: 1...10)
.labelsHidden()
Text("\(quantity)")
.frame(width: 30)
Button("Add to Cart") {
addToCart()
}
.padding(.horizontal, 12)
.padding(.vertical, 6)
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(6)
}
.padding(.vertical, 4)
}
private func addToCart() {
if let existingIndex = cartItems.firstIndex(where: { $0.product.id == product.id }) {
cartItems[existingIndex].quantity += quantity
} else {
let newItem = CartItem(product: product, quantity: quantity)
cartItems.append(newItem)
}
quantity = 1 // Reset quantity after adding
}
}
// Cart View
struct CartView: View {
@Binding var cartItems: [CartItem]
@Environment(\.presentationMode) var presentationMode
var totalPrice: Double {
cartItems.reduce(0) { $0 + ($1.product.price * Double($1.quantity)) }
}
var body: some View {
NavigationView {
VStack {
if cartItems.isEmpty {
Text("Your cart is empty")
.font(.title2)
.foregroundColor(.secondary)
.padding()
Spacer()
} else {
List {
ForEach(cartItems) { item in
CartItemRowView(
cartItem: item,
cartItems: $cartItems
)
}
.onDelete(perform: deleteItems)
}
VStack {
HStack {
Text("Total: $\(String(format: "%.2f", totalPrice))")
.font(.title2)
.fontWeight(.bold)
Spacer()
}
Button("Checkout") {
// Checkout logic here
cartItems.removeAll()
presentationMode.wrappedValue.dismiss()
}
.frame(maxWidth: .infinity)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
.padding()
}
}
.navigationTitle("Shopping Cart")
.navigationBarItems(trailing: Button("Close") {
presentationMode.wrappedValue.dismiss()
})
}
}
private func deleteItems(offsets: IndexSet) {
cartItems.remove(atOffsets: offsets)
}
}
// Cart Item Row View
struct CartItemRowView: View {
let cartItem: CartItem
@Binding var cartItems: [CartItem]
var body: some View {
HStack {
VStack(alignment: .leading) {
Text(cartItem.product.name)
.font(.headline)
Text("$\(String(format: "%.2f", cartItem.product.price)) each")
.foregroundColor(.secondary)
}
Spacer()
QuantityControlView(
cartItem: cartItem,
cartItems: $cartItems
)
}
.padding(.vertical, 4)
}
}
// Quantity Control View
struct QuantityControlView: View {
let cartItem: CartItem
@Binding var cartItems: [CartItem]
var body: some View {
HStack {
Button("-") {
updateQuantity(-1)
}
.frame(width: 30, height: 30)
.background(Color.red)
.foregroundColor(.white)
.cornerRadius(6)
Text("\(cartItem.quantity)")
.frame(width: 40)
Button("+") {
updateQuantity(1)
}
.frame(width: 30, height: 30)
.background(Color.green)
.foregroundColor(.white)
.cornerRadius(6)
}
}
private func updateQuantity(_ change: Int) {
if let index = cartItems.firstIndex(where: { $0.id == cartItem.id }) {
let newQuantity = cartItems[index].quantity + change
if newQuantity <= 0 {
cartItems.remove(at: index)
} else {
cartItems[index].quantity = newQuantity
}
}
}
}
// Preview
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ShoppingAppView()
}
}
Best Practices / Thực Hành Tốt Nhất
English:
Use
@Statefor local view state - Keep it private and use it only within the view that owns the dataUse
@Bindingfor shared state - When you need to pass state between parent and child viewsSingle source of truth - The parent view should own the state, child views should only have bindings
Naming conventions - Use descriptive names and mark
@Stateproperties as private
Vietnamese:
Sử dụng
@Statecho trạng thái cục bộ của view - Giữ nó private và chỉ sử dụng trong view sở hữu dữ liệuSử dụng
@Bindingcho trạng thái chia sẻ - Khi bạn cần truyền trạng thái giữa view cha và conNguồn sự thật duy nhất - View cha nên sở hữu trạng thái, view con chỉ nên có binding
Quy ước đặt tên - Sử dụng tên mô tả rõ ràng và đánh dấu các thuộc tính
@Statelà private
Common Mistakes to Avoid / Lỗi Thường Gặp Cần Tránh
English:
Don't use
@Statefor data that should be shared between viewsDon't forget to use
$when passing bindings to child viewsDon't make
@Stateproperties publicDon't use
@Bindingin the root view (use@Stateinstead)
Vietnamese:
Đừng sử dụng
@Statecho dữ liệu cần được chia sẻ giữa các viewĐừng quên sử dụng
$khi truyền binding xuống view conĐừng để thuộc tính
@Statelà publicĐừng sử dụng
@Bindingtrong view gốc (thay vào đó hãy dùng@State)
Noted:
This generated by AI. This may be not correct information.