1

下面的代码在几个地方的示例中找到并且曾经为我工作,但现在它崩溃了。问题似乎出在 iPadOS 上,因为它似乎适用于 iPhone,包括模拟器和物理设备。

错误是:

'UIPopoverPresentationController (<UIPopoverPresentationController: 0x155e1b5f0>) 应该在演示发生之前设置一个非零的 sourceView 或 barButtonItem。以 NSException 类型的未捕获异常终止

这是 iPadOS 上的错误还是我做错了什么?

import SwiftUI

struct ContentView: View {
    @State var showSheet = false
    var body: some View {
        Button(action: actionSheet)
        {
            Label("", systemImage: "square.and.arrow.up")
        }
    }
    
    func actionSheet() {
        let av = UIActivityViewController(activityItems: ["Testing"], applicationActivities: nil)
        UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

4

1 回答 1

1

在看到 lorem ipsum 的回复后,我改变了以下内容,它适用于 iOS 15 及之前的版本。

func actionSheet() {
        let av = UIActivityViewController(activityItems: ["Testing"], applicationActivities: nil)
        
        av.popoverPresentationController?.sourceView = HostingView(rootView: self)
        UIApplication.shared.windows.first?.rootViewController?.present(av, animated: true, completion: nil)
    }
    
    class HostingView<T: View>: UIView {
        
        private(set) var hostingController: UIHostingController<T>
        
        var rootView: T {
            get { hostingController.rootView }
            set { hostingController.rootView = newValue }
        }
        
        init(rootView: T, frame: CGRect = .zero) {
            hostingController = UIHostingController(rootView: rootView)
            
            super.init(frame: frame)
            
            backgroundColor = .clear
            hostingController.view.backgroundColor = backgroundColor
            hostingController.view.frame = self.bounds
            hostingController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
            
            addSubview(hostingController.view)
        }
        
        required init?(coder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
于 2021-09-08T19:29:26.197 回答