How can one have a list where each item in the list contains a Link
and a NavigationLink
?
When putting the Link
and NavigationLink
next to each other in an HStack
both get triggered wherever I tap on the row.
struct ContentView: View {
var body: some View {
NavigationView {
List {
HStack {
Link(
"Link",
destination: URL(string: "https://www.apple.com")!
)
NavigationLink(
"Other View",
destination: Text("Hello from other view"))
}
}
}
}
}
CodePudding user response:
The second parameter to NavigationLink
is the content of the table cell and can be a generic view. Likely you would like something like:
NavigationView {
NavigationLink(destination: Text("Hello from other view")) {
HStack {
Link("Link", destination: URL(string: "https://www.apple.com")!)
Text("Other View")
}
}
}
CodePudding user response:
Teensy bit hacky, but if a onTapGesture
is added to the Link
that explicity opens the URL. Then that gets fired for the Link
instead of the navigate link event that List
implicity adds to each row when it's embedded in a NavigationView
.
Something like the following works for me with Xcode 13 beta/ ios 15 and macOS 12 beta.
struct ContentView: View {
@Environment(\.openURL) private var openURL
let url = URL(string: "https://www.apple.com")
var body: some View {
NavigationView {
List {
HStack {
Link(
"Link",
destination: url!
)
.onTapGesture {
print("Opening URL \(url)")
openURL(url!)
}
NavigationLink(
"Other View",
destination: Text("Hello from other view")
)
}
}
}
}
}