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

4

我希望在我的macOS应用程序中显示一个用户可以点击的链接。目前我已经有了以下内容:

Text(url)
.onTapGesture {
    if let url = URL(string: self.url) {
        NSWorkspace.shared.open(url)
    }
}

然而,这并没有为用户提供可点击的URL的视觉指示。我希望文本有下划线,当用户悬停在其上时,光标会变成手形。我该如何做到这一点?
编辑:我在Swift论坛中找到了一个自定义扩展,用于有条件地对视图应用修改器。

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

2个回答

4

下面是可能的解决方案。 已在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()
    }
}

谢谢!唯一缺失的是当用户将鼠标悬停在上面时,使文本变为下划线。 - Peter Schorn

1
不要使用“文本”来实现此功能。
您需要使用按钮:
Button("someLink") {
    FS.openTerminal(at: Urls.SshDir)
}
.buttonStyle(LinkButtonStyle())

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接