[英]How to switch to another view by each element's onTapGesture of a list in SwiftUI?
[英]SwiftUI List Row onTapGesture to handle Push
person
变量的 DetailView: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
数据: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.
// ???
}
}
}
})
}
}
最后,我找到了修复它的方法。 感谢@William Hu 在这篇文章中SwiftUI NavigationLink:如何在显示目标视图之前调用函数
具体来说,对于我的问题:
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)")
}
})
}
})
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.