【问题标题】:在 SwiftUI macOS 11 中的链接点击/点击上运行一些代码
【发布时间】:2022-01-23 05:18:19
【问题描述】:

我有一个 macOS SwiftUI 小部件(使用 WidgetKit),支持的最低操作系统版本设置为 11。这个细节很重要,因为我想在用户单击/点击链接视图时运行一些代码:

Link("StackOverflow.com", destination: URL(string: "https://www.stackoverflow.com/")!)
  .environment(\.openURL, OpenURLAction { url in
    print("hello, world")
    return .systemAction
  }
)

这仅适用于 SwiftUI: use Link with onTapGesture 中指定的 macOS 12+,因为 it's a read-only property in macOS 11。如何让它在 macOS 11 上运行?我试过了

  1. onTapGesture 添加一个永远不会被调用的处理程序
  2. 为永远不会被调用的父 HStack 添加一个 onTapGesture
  3. 从链接的onOpenURL 处理程序发布通知并在HStack 的onReceive 中接收通知(参考How to set addObserver in SwiftUI?
  4. 删除了 Link 并将其设置为 Button 并设置了 action:,但处理程序似乎从未被调用

徒劳。

【问题讨论】:

  • 你想在那个动作中做什么?我只是试图了解解决方法的可能方向。

标签: macos swiftui hyperlink widgetkit


【解决方案1】:

您可以尝试使用一个简单的按钮,相当于“...单击链接视图时运行一些代码...”,例如:

struct ContentView: View {
    var body: some View {
        Button(action: {
            if let url = URL(string: "https://stackoverflow.com") {
                // NSWorkspace.shared.open(url)  // simple alternative
                NSWorkspace.shared.open(url, configuration: NSWorkspace.OpenConfiguration(), completionHandler: { app, error in
                    print("----> opening url: \(url)")
                })
            }
        }) {
            Text("StackOverflow.com")
        }
        .frame(width: 444, height: 444)
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-28
    • 2018-07-30
    • 2020-06-07
    • 2014-02-24
    • 1970-01-01
    • 2022-01-03
    • 2023-01-29
    • 2010-11-19
    相关资源
    最近更新 更多