Example: This code shows
1) the different between @Published variable and non-published variable. @Published
variable can be modified and real-time in body view
non-published variable can only be modified in init
, namely before body view rendered.
2) ObservableObject
can have normal attributes (var and static let) + @Published attribute.
import SwiftUI
struct ContentView: View {
@ObservedObject var userManager: UserManager
init() {
userManager = UserManager()
userManager.displayName = "ok"
}
var body: some View {
VStack( spacing: 50) {
Text(userManager.displayName ?? "no")
if userManager.isLogged {
Text( "Logged in")
Button(action: userManager.logOut) {
Text("Log out")
}
} else {
Text( "Logged out")
Button(action: userManager.logIn) {
Text("Log in")
}.onAppear {
userManager.displayName = "ok"
}
}
} // VStack
} // body
}
class UserManager: ObservableObject {
@Published var username: String?
var displayName: String?
static let screenWidth: CGFloat = UIScreen.main.bounds.width
var isLogged: Bool {
username != nil
}
func logOut() {
username = nil
print(screenWidth)
}
func logIn() {
username = "Demo"
print(screenWidth)
}
}