【问题标题】:UIButton in SwiftUI Catalyst Mac app doesn't work when clicked second timeSwiftUI Catalyst Mac 应用程序中的 UIButton 在第二次单击时不起作用
【发布时间】:2021-12-26 08:38:45
【问题描述】:

这是我的代码:

private struct ShareButton: UIViewRepresentable {
    func makeUIView(context: Context) -> UIButton {
        let activityViewController = UIActivityViewController(activityItems: [URL(string: "https://www.apple.com/")!], applicationActivities: nil)
        let action = UIAction(title: "Share") { _ in UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController?.present(activityViewController, animated: false) }
        let button = UIButton(primaryAction: action)
        activityViewController.popoverPresentationController?.sourceView = button
        return button
    }
    func updateUIView(_ uiView: UIButton, context: Context) { }
}

基本上它是创建一个带有UIActionUIButton,其中有一个UIActivityViewControllersourceView 设置为共享菜单为UIButton

这里是问题的演示:

UIButton 在创建 SwiftUI 视图时创建,并设置为 sourceView。我的猜测是出现问题是因为 UIButton 由于某些 SwiftUI 机制而以某种方式被破坏和重新创建?不过,我可能完全错了。无论如何要解决这个问题?

或者以任何其他方式在 SwiftUI Catalyst Mac 应用程序中执行共享按钮?

【问题讨论】:

标签: swiftui uibutton uikit uiactivityviewcontroller mac-catalyst


【解决方案1】:

“或任何其他方式在 SwiftUI Catalyst Mac 应用程序中执行共享按钮?”

您可以尝试这种方法,使用以下扩展名: How to get rid of message " 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead" with AdMob banner?

public extension UIApplication {
    func currentUIWindow() -> UIWindow? {
        let connectedScenes = UIApplication.shared.connectedScenes
            .filter({
                $0.activationState == .foregroundActive})
            .compactMap({$0 as? UIWindowScene})

        let window = connectedScenes.first?
            .windows
            .first { $0.isKeyWindow }

        return window

    }
}

struct ContentView: View {
    let holaTxt = "Hola ? "
    
    var body: some View {
        Button(action: {
            let AV = UIActivityViewController(activityItems: [holaTxt], applicationActivities: nil)
            UIApplication.shared.currentUIWindow()?.rootViewController?.present(AV, animated: true, completion: nil)
        }) {
            Text("Share")
        }
    }
}

【讨论】:

  • 规避弃用的好方法,但它不能解决 sourceView 被我遗忘的问题
  • 什么是sourceView
【解决方案2】:

找到了一个优雅的解决方案,用于在 SwiftUI Catalyst Mac 应用(实际上是所有 SwiftUI 应用)中创建分享按钮,请参阅 https://github.com/SwiftUI-Plus/ActivityView

【讨论】:

  • 当链接到您自己的网站或内容(或您附属的内容)时,您必须disclose your affiliation in the answer,以免它被视为垃圾邮件。根据 Stack Exchange 政策,在您的用户名中包含与 URL 相同的文本或在您的个人资料中提及它不被视为充分披露。
  • @Tyler2P wdym?那不是我的内容
猜你喜欢
  • 2012-07-09
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 2015-11-25
  • 2019-04-23
相关资源
最近更新 更多