Thuta Learning
ရှာဖွေရန်
IntermediateMobile Developmentintermediate

State in SwiftUI (@State, @Binding)

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

ဒီခန်းပြီးရင် ဘာတတ်သွားမလဲ

  • State in SwiftUI (@State, @Binding) ကို ကြောက်စရာမလိုအောင် နားလည်မယ်
  • ကိုယ်တိုင် Xcode/SwiftUI code ကို run ကြည့်တတ်မယ်
  • Real project ထဲမှာ ဒီ concept ကို ချက်ချင်း အသုံးချတတ်မယ်

ခဏလေး ဒီလိုပဲ စဉ်းစားကြည့်

SwiftUI View က struct ဆိုတော့ immutable ပါ — `var count = 0` ကို View ထဲ ရေးထားရင် value ကို modify လုပ်လို့ မရပါဘူး (compile error)။ `@State private var count = 0` ကို သုံးမှသာ SwiftUI က value ကို View ရဲ့ 'ကျောပေါင်း' မှာ ခွဲသိမ်းထားပေးပြီး, value ပြောင်းတိုင်း View ကို automatic re-render ပေးပါတယ်။ `@Binding` ကတော့ parent ရဲ့ `@State` ကို child View ဆီ 'ချိတ်ဆက်' ပေးတဲ့ property wrapper ပါ — child က value ကို modify လုပ်ရင် parent ရဲ့ state ကိုပါ ချက်ချင်း update ပေးပါတယ် (State Hoisting pattern, Compose နဲ့ ဆင်တူပါတယ်).

လက်တွေ့ scenario နဲ့ ချိတ်ကြည့်မယ်

Counter app တစ်ခုမှာ `@State private var count = 0` ရေးထားပြီး, Button tap ရင် `count += 1` လုပ်ရင် — screen ပေါ်က `Text("\(count)")` က automatic update ဖြစ်ပြီး number တက်သွားတာ တွေ့ရမှာပါ။ `@Binding` ကို သုံးရင် `ToggleSwitch(isOn: $isEnabled)` ဆိုပြီး state ကို parent ကနေ `$` prefix နဲ့ ချိတ်ဆက်ပေးပြီး, `ToggleSwitch` View ကို parent ကွဲပြားစွာ reuse လုပ်နိုင်ပါတယ်.

အတူတူ ကြည့်မယ်

swift
struct Counter: View {
    @State private var count = 0

    var body: some View {
        VStack {
            Text("Count: \(count)")
                .font(.title)
            Button("Increment") {
                count += 1
            }
        }
    }
}
You should see
Button ကို tap ရင် 'Count: 0' → 'Count: 1' → 'Count: 2' ဆိုပြီး screen ပေါ် live update ဖြစ်နေတာ တွေ့ရမည်။

၅ မိနစ် စမ်းကြည့်

`Counter` View ကို run ကြည့်ပြီး Button ကို ၅ ကြိမ် tap ကြည့်ပါ — count ရဲ့ value live update ဖြစ်နေတာ confirm လုပ်ကြည့်ပါ။ ပြီးရင် `@State` ကို ဖျက်ကြည့်ပြီး ဘယ်လို compile error တွေ့ရလဲ ကြည့်ကြည့်ပါ။

သတိလေးတစ်ချက်

`@State` ကို View ရဲ့ 'local, private' state အတွက်ပဲ သုံးပါ — app-wide state (user login status) အတွက်ကတော့ `@State` မဟုတ်ဘဲ `ObservableObject` (Advanced chapter) ကို သုံးသင့်ပါတယ်။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • `@State` မပါဘဲ View property ကို modify လုပ်ဖို့ ကြိုးစားခြင်း — compile error ('Cannot assign to property') တွေ့ရနိုင်ပါတယ်
  • `@State` ကို public/external property အနေနဲ့ expose ဖို့ ကြိုးစားခြင်း — `@State` က private ဖြစ်သင့်ပါတယ်, parent ဆီ share ချင်ရင် `@Binding` သုံးပါ

အခု ကိုယ်တိုင် စမ်းကြည့်

`Counter` View ကို run ကြည့်ပြီး Button ကို ၅ ကြိမ် tap ကြည့်ပါ — count ရဲ့ value live update ဖြစ်နေတာ confirm လုပ်ကြည့်ပါ။ ပြီးရင် `@State` ကို ဖျက်ကြည့်ပြီး ဘယ်လို compile error တွေ့ရလဲ ကြည့်ကြည့်ပါ။

You'll know it worked when: Button ကို tap ရင် 'Count: 0' → 'Count: 1' → 'Count: 2' ဆိုပြီး screen ပေါ် live update ဖြစ်နေတာ တွေ့ရမည်။

State in SwiftUI (@State, @Binding) | Thuta Learning