ios – Swiftui View Modifications upon Inputting Knowledge?


I am new to coding and Swiftui normally so apologies if it is a silly one. I’ve an app which makes use of navigation view. The method goes as following: on web page 1 you enter knowledge in textfields, after which press a subsequent button to navigate to web page 2 the place you’re introduced with a graph primarily based on the info from web page 1. On web page 2 I used the perform beneath to take that graph and render and reserve it as a PDF.

The issue is, I run the perform and save the view as pdf on web page 2, then I am going again to web page 1 to re-enter knowledge, and as quickly as I faucet on a textfield I get a view of the graph pop up on the display and all else is gone, the app is actually crashed.

   func exportToPDF() {
        let outputFileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!.appendingPathComponent("C182-CG.pdf")
        let pageSize = CGSize(width: UIScreen.foremost.bounds.width, peak: UIScreen.foremost.bounds.peak)
        //View to render on PDF
        var myUIHostingController = UIHostingController(rootView: graph_182)
        myUIHostingController.view.body = CGRect(origin: .zero, measurement: pageSize)

        //Render the view behind all different views     
        guard let rootVC =  UIApplication.shared.connectedScenes.flatMap({ ($0 as? UIWindowScene)?.home windows ?? [] }).first(the place: { $0.isKeyWindow })?.rootViewController else {
            print("ERROR: Couldn't discover root ViewController.")
//      at: 0 -> attracts behind all different views
//      at: UIApplication.shared.home windows.rely -> attract entrance
        rootVC.view.insertSubview(myUIHostingController.view, at: 0)

//        Render the PDF
        let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(origin: .zero, measurement: pageSize))
        DispatchQueue.foremost.async {
            do {
                attempt pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
                    myUIHostingController.view.layer.render(in: context.cgContext)
                print("wrote file to: (outputFileURL.path)")
            } catch {
                print("Couldn't create PDF file: (error.localizedDescription)")

Via trial and error I used to be capable of slender down the issue to this line of code inside the perform:

rootVC.view.insertSubview(myUIHostingController.view, at: 0)

Logically, I suppose I would wish to un-insert/take away the subview on the finish of the perform. With my information of swift I’m restricted right here, please let me know of any options.


Leave a Reply