[英]SwiftUI: Link together with NavigationLink as list item
How can one have a list where each item in the list contains a Link
and a NavigationLink
?如何获得一个列表,其中列表中的每个项目都包含一个
Link
和一个NavigationLink
?
When putting the Link
and NavigationLink
next to each other in an HStack
both get triggered wherever I tap on the row.当在
HStack
中将Link
和NavigationLink
彼此相邻放置时,只要我点击该行,它们都会被触发。
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"))
}
}
}
}
}
Turns out the way Apple recommend to do this is to explicitly set the style on the Link
button.结果表明 Apple 推荐的方法是明确设置
Link
按钮的样式。 eg例如
struct ContentView: View {
var body: some View {
NavigationView {
List {
HStack {
Link(
"Link",
destination: URL(string: "https://www.apple.com")!
)
.buttonStyle(.borderless) // <-- add this
NavigationLink(
"Other View",
destination: Text("Hello from other view"))
}
}
}
}
}
Answer based on excellent notes over here https://swiftui-lab.com/random-lessons/ .答案基于此处https://swiftui-lab.com/random-lessons/的优秀笔记。 Do wish Apple would improve their SwiftUI docs!
真希望 Apple 能改进他们的 SwiftUI 文档!
Previous, it worked, but don't really recommend way of doing it by adding onTapGesture
to the Link
that explicity opens the URL. left below for context.以前,它有效,但并不真正推荐通过将
onTapGesture
添加到显式打开 URL 的Link
来实现它的方法。在下面留下上下文。
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")
)
}
}
}
}
}
Based on shufflingb's answer:根据 shufflingb 的回答:
Replace the link with a non-tappable element and add a gesture handler to it.用不可点击的元素替换链接并向其添加手势处理程序。
struct ContentView: View {
@Environment(\.openURL) private var openURL
let url = URL(string: "https://www.apple.com")
var body: some View {
NavigationView {
List {
HStack {
Text("Link")
.foregroundColor(.accentColor)
.onTapGesture {
openURL(url!)
}
NavigationLink(
"Other View",
destination: Text("Hello from other view")
)
}
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.