Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pbrewczynski/63f2dfdba96dec2efcf7d81d304622f6 to your computer and use it in GitHub Desktop.
Save pbrewczynski/63f2dfdba96dec2efcf7d81d304622f6 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")])
}
}
}
@Bitcosoftware
Copy link

I am not sure if this helps or if the answers on Stack Overflow got you the result you needed, but I found that this works.

Take out line 44.

Then right after line 64, put it there. Put .id(c). This will reset the stateobject. At least this worked for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment