Last active
October 17, 2023 17:00
-
-
Save devs-rootstrap/42f5e72610502370926ed7d17cfe5e57 to your computer and use it in GitHub Desktop.
Exploring SwiftUI’s Data Flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct ContentView: View { | |
@AppStorage("username") var username: String = "guest" | |
var body: some View { | |
VStack { | |
Text("Welcome, \(username)!") | |
TextField("Enter your username", text: $username) | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct MyView: View { | |
@State var myState = "Hello, world!" | |
var body: some View { | |
TextField("Enter some text", text: $myState) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserData: ObservableObject { | |
@Published var name: String = "John" | |
@Published var age: Int = 30 | |
} | |
struct ContentView: View { | |
@EnvironmentObject var userData: UserData | |
var body: some View { | |
VStack { | |
Text("Name: \(userData.name)") | |
Text("Age: \(userData.age)") | |
ChildView() | |
} | |
} | |
} | |
struct ChildView: View { | |
@EnvironmentObject var userData: UserData | |
var body: some View { | |
VStack { | |
Text("Name: \(userData.name)") | |
Text("Age: \(userData.age)") | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyModel: ObservableObject { | |
@Published var items: [String] = [] | |
@Published var selectedItem: String? | |
} | |
struct MyMasterView: View { | |
@StateObject var model: MyModel | |
var body: some View { | |
List(model.items) { item in | |
Text(item) | |
.onTapGesture { | |
model.selectedItem = item | |
} | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@State var myState = "Hello, world!" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment