SwiftUI macOS 10.15下替代Link组件打开外部链接的实现方案
兼容 macOS 10.15 的 SwiftUI 外部链接打开方案
SwiftUI 原生 Link 组件最低仅支持 macOS 11.0 版本,要向下兼容 10.15 可以通过自定义组件实现,核心调用 macOS 早期版本就支持的 NSWorkspace 接口打开外部链接。
最简实现方案
自定义一个和原生 Link 用法一致的兼容组件,直接替换原有代码即可:
import SwiftUI import AppKit // 编译提示找不到NSWorkspace时添加该行即可 struct CompatibleLink: View { let title: String let destination: URL init(_ title: String, destination: URL) { self.title = title self.destination = destination } var body: some View { Text(title) // 匹配系统链接样式,可自行调整 .foregroundColor(.blue) .underline() .onTapGesture { NSWorkspace.shared.open(destination) } // 鼠标悬停时显示手型光标 .onHover { isHovering in if isHovering { NSCursor.pointingHand.push() } else { NSCursor.pop() } } } } // 调用方式和原生Link完全一致 var body: some View { if let appleURL = URL(string: "https://www.apple.com") { CompatibleLink("Visit Apple", destination: appleURL) } }
多版本兼容优化
如果希望高版本系统仍使用原生 Link 组件,可添加版本判断逻辑:
var body: some View { if let appleURL = URL(string: "https://www.apple.com") { if #available(macOS 11.0, *) { Link("Visit Apple", destination: appleURL) } else { CompatibleLink("Visit Apple", destination: appleURL) } } }
内容的提问来源于stack exchange,提问作者swiftnoob
相关产品推荐
相关产品推荐

