gpt4 book ai didi

SwiftUI macOS - 创建可点击的超链接

转载 作者:行者123 更新时间:2023-12-05 02:53:39 24 4
gpt4 key购买 nike

我想在我的 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()
}
}

preview

最佳答案

这是可能的解决方案。使用 Xcode 11.4/macOS 10.15.4 测试

demo

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com