【问题标题】:SwiftUI Share Sheet Crashes iPadSwiftUI Share Sheet 让 iPad 崩溃
【发布时间】:2021-04-13 16:21:24
【问题描述】:

我正在关注本教程https://jeevatamil.medium.com/how-to-create-share-sheet-uiactivityviewcontroller-in-swiftui-cef64b26f073

向我的 swiftui 应用程序添加一个简单的共享表。它在 iPhone 上正常工作,但在 iPad 上崩溃并出现此错误

Terminating app due to uncaught exception 'NSGenericException', reason: 'UIPopoverPresentationController (<UIPopoverPresentationController: 0x107d95ee0>) should have a non-nil sourceView or barButtonItem set before the presentation occurs.'

有什么办法可以解决这个错误?不完全确定这里发生了什么。谢谢!

【问题讨论】:

  • 欢迎来到 SO。与其发布代码链接(可能会过时),不如在代码中包含minimal reproducible example 通常是一个更好的主意。看一眼该教程,您可以尝试将 sourceView 设置为根视图控制器的视图,但您可以使用 UIViewControllerRepresentable 找到更好的运气:stackoverflow.com/a/58341956/560942

标签: swift swiftui swift5 uiactionsheet


【解决方案1】:

尝试使用此代码在 iPad 中打开 Actionsheet。

if let vc = UIApplication.shared.windows.first?.rootViewController{
        let activityVC = UIActivityViewController(activityItems: [urlShare], applicationActivities: nil)
        if isIpad{
            activityVC.popoverPresentationController?.sourceView = vc.view
            activityVC.popoverPresentationController?.sourceRect = .zero
        }
        UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
    }

【讨论】:

    【解决方案2】:

    您只需在UIActivityViewControllerpopoverPresentationController 上设置sourceViewsourceRect。这是一个比我迄今为止看到的更完整和正确的示例:

    // Get a scene that's showing (iPad can have many instances of the same app, some in the background)
    let activeScene = UIApplication.shared.connectedScenes.first(where: { $0.activationState == .foregroundActive }) as? UIWindowScene
            
    let rootViewController = (activeScene?.windows ?? []).first(where: { $0.isKeyWindow })?.rootViewController
            
    // iPad stuff (fine to leave this in for all iOS devices, it will be effectively ignored when not needed)
    activityVC.popoverPresentationController?.sourceView = rootViewController?.view
    activityVC.popoverPresentationController?.sourceRect = .zero
            
    rootViewController?.present(activityVC, animated: true, completion: nil)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 2019-11-08
      • 2015-10-13
      • 1970-01-01
      • 2020-04-18
      • 2021-01-31
      • 1970-01-01
      相关资源
      最近更新 更多