Swift UI : Observable, Observed, State and Binding

State and Binding

@State and @Binding are used when you need to pass a variable to another view. 


struct ContentView: View {

@State var showLogo = true
var body: some View {
VStack {
if showLogo {
LittleLemonLogo(bindingVariable: $showLogo)
}
}
}
}

@State to controlling a variable "showLogo"

struct LittleLemonLogo: View {
@Binding var bindingVariable:Bool
var body: some View {
VStack {
Image("littleLemonLogo")
Button(action: {
bindingVariable.toggle()
}, label: {
Text("Toggle Logo Visibility")
.font(.title2)
})
}
}
}


A Boolean variable named bindingVariable of type @Binding is created on line 1. This variable will receive the state of ContentView's showLogo variable and will be tied to it, meaning, that any change to bindingVariable will change showLogo.

ObservableObject and ObservedObject

@State & @Binding for variable

If you want to have a controlling variable in a class?

@ObservableObject to the rescue!

class MyClass:ObservableObject {
@Published var showLogo = true
}

variable showLogo marked as @Published, meaning, its changes will be notified to those observing it

struct ContentView: View {
@ObservedObject var myClass = MyClass()
var body: some View {
VStack {
if myClass.showLogo {
LittleLemonLogo(myClass: myClass)
}
}
}
}

struct LittleLemonLogo: View {
var myClass:MyClass
var body: some View {
VStack {
Image("littleLemonLogo")
Button(action: {
myClass.showLogo.toggle()
}, label: {
Text("Toggle Logo Visibility OFF")
.font(.title2)
})
}
}
}

myClass to store the instance of MyClass received from ContentView




Nhận xét

Bài đăng phổ biến từ blog này

Flutter 4.5 - Custom theme, font, image

Flutter 1.2 - Flutter Architecture

Flutter 2.5 - First App | Building a Widget Tree