Skip to content

Instantly share code, notes, and snippets.

@pbrewczynski
Created October 24, 2022 08:31
Show Gist options
  • Save pbrewczynski/5706c4843a6ec7cc41c25bf304a66515 to your computer and use it in GitHub Desktop.
Save pbrewczynski/5706c4843a6ec7cc41c25bf304a66515 to your computer and use it in GitHub Desktop.
import Foundation
import SwiftUI
final class Contact: ObservableObject, Identifiable {
let id = UUID()
@Published var name: String
@Published var city: String
@Published var profile: String
init(name: String, city: String, profile: String) {
self.name = name
self.city = city
self.profile = profile
}
}
class ImageLoader: ObservableObject {
var image: String = ""
init() {
print("Initializer of Image Loader was called")
}
func load(image: String) {
print("Brrr.... loading image")
print("The image is: \(image)")
self.image = image
}
}
struct Detail: View {
@ObservedObject var contact: Contact
@StateObject var loader = ImageLoader()
var body: some View {
HStack {
Text(loader.image) // mocked image
VStack {
Text(contact.name).bold()
Text(contact.city)
}
}
.id(contact.id)
.onAppear {
loader.load(image: contact.profile)
}
}
}
struct ContentView: View {
@State var selection: Contact?
var contacts: [Contact]
var body: some View {
HStack {
ForEach(contacts) { contact in
Button(contact.name) {
self.selection = contact
}
}
}
if let c = selection {
Detail(contact: c)
}
}
}
@main
struct SwiftUILearning2App: App {
var body: some Scene {
WindowGroup {
ContentView(contacts: [ Contact(name: "name1", city: "city1", profile: "profile_1"),
Contact(name: "name2", city: "city2", profile: "profile_2")])
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment