我想在我的 macOS 应用程序中显示一个用户可以点击的 url。我到目前为止是这样的:
Text(url)
.onTapGesture {
if let url = URL(string: self.url) {
NSWorkspace.shared.open(url)
}
}
但是,这不会向用户提供该 url 可点击的视觉指示。我希望文本带有下划线,并且当用户将鼠标悬停在它上面时,我希望光标变为一只手。我该怎么做?
编辑:
我找到了一个自定义扩展,用于有条件地将修饰符应用于 swift forums 中的 View 。 :
extension View {
func `if`<Content: View>(_ conditional: Bool, content: (Self) -> Content) -> some View {
if conditional {
return AnyView(content(self))
} else {
return AnyView(self)
}
}
}
将它与@Asperi 的回答结合后,我现在有了这个:
@State private var isHoveringOverURL = false
Button(action: {
if let url = URL(string: self.url) {
NSWorkspace.shared.open(url)
}
}) {
Text(self.url)
.font(.caption)
.foregroundColor(Color.blue)
.if(isHoveringOverURL) {
$0.underline()
}
}
.buttonStyle(PlainButtonStyle())
.onHover { inside in
if inside {
self.isHoveringOverURL = true
NSCursor.pointingHand.push()
} else {
self.isHoveringOverURL = false
NSCursor.pop()
}
}
最佳答案
这是可能的解决方案。使用 Xcode 11.4/macOS 10.15.4 测试
Button(action: {
// link action here
}) {
Text("www.stackoverflow.com").underline()
.foregroundColor(Color.blue)
}.buttonStyle(PlainButtonStyle())
.onHover { inside in
if inside {
NSCursor.pointingHand.push()
} else {
NSCursor.pop()
}
}
关于SwiftUI macOS - 创建可点击的超链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62112868/