person
variable:struct DetailView: View {
let person: Person
var body: some View {
VStack {
Text("Person Name: \(person.name)")
Text("Person Email: \(person.email)")
}
}
}
class Person: Identifiable {
let id = UUID()
let name: String
let email: String
init(name: String, email: String) {
self.name = name
self.email = email
}
}
struct ContentView: View {
private let personIDs: [String] = ["xx1", "xx2", "xx3", "xx4", "xx5"]
var body: some View {
NavigationView(content: {
List(self.personIDs, id: \.self) { personID in
Text("personID: \(personID)")
}
})
}
}
struct ContentView: View {
private let personIDs: [String] = ["xx1", "xx2", "xx3", "xx4", "xx5"]
var body: some View {
NavigationView(content: {
List(self.personIDs, id: \.self) { personID in
Text("personID: \(personID)")
.onTapGesture {
// Load Person data (by `personID`) from server.
// How can I push to DetailView here?
}
}
})
}
}
person
data for DetailView initializing:struct ContentView: View {
private let personIDs: [String] = ["xx1", "xx2", "xx3", "xx4", "xx5"]
var body: some View {
NavigationView(content: {
List(self.personIDs, id: \.self) { personID in
// `person` argument is non-optional
// no `person: Person` data here
NavigationLink(destination: DetailView(person: /* ??? */)) {
Text("personID: \(personID)")
.onTapGesture {
// Load Person data (by `personID`) from server.
// ???
}
}
}
})
}
}
Finally, I founded a way to fix it. Thanks to @William Hu on this article SwiftUI NavigationLink: how to call a function before showing destination view
Specifically, for my problem:
struct ContentView: View {
private let personIDs: [String] = ["xx1", "xx2", "xx3", "xx4", "xx5"]
@State private var person: Person = Person(name: "", email: "")
@State private var navigationLinkTriggerer: String? = nil
var body: some View {
NavigationView(content: {
List(self.personIDs, id: \.self) { personID in
Button(action: {
// --- --- ---
// Simulate loading data from server
self.person = Person(name: "\(personID) Name", email: "\(personID)@gmail.com")
// ---
// Completion Handler
self.navigationLinkTriggerer = personID
// ---
// --- --- ---
}, label: {
NavigationLink(destination: DetailView(person: person),
tag: personID,
selection: self.$navigationLinkTriggerer) {
Text("personID: \(personID)")
}
})
}
})
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.