swiftswiftuipdfviewswiftui-environment

Accessing @Environment(\.presentationMode) stopping PDFView from appearing


Problem: Accessing @Environment(.presentationMode) stops my PDFView from being shown.

Working Code: Displays a pdf document via PDFViewer within MainView

import SwiftUI

struct MainView: View {

    @State var pdfDocument: PDFDocument = PDFDocument()

    var body: some View {

        VStack {

            PDFViewer(pdfDocument: $pdfDocument)
        }
    }
}

import SwiftUI
import PDFKit

struct PDFViewer UIViewRepresentable {

    @Binding var pdfDocument: PDFDocument
    let pdfView = PDFView()

    func makeUIView(context: Context) -> some UIView {
        pdfView.document = pdfDocument
        pdfView.autoScales = true
        return pdfView
    }

    func updateUIView(_ uiView: UIViewType, context: Context) {
        print("update view called")
        pdfView.document = pdfDocument
    }
}

Broken Code: Doesnt display the document nor PDFViewer (only change is accessing @Environment)

import SwiftUI

struct MainView: View {

    @Environment(\.presentationMode) var presentationMode

    @State var pdfDocument: PDFDocument = PDFDocument()

    var body: some View {

        VStack {

            PDFViewer(pdfDocument: $pdfDocument)
        }
    }
}

import SwiftUI
import PDFKit

struct PDFViewer UIViewRepresentable {

    @Binding var pdfDocument: PDFDocument
    let pdfView = PDFView()

    func makeUIView(context: Context) -> some UIView {
        pdfView.document = pdfDocument
        pdfView.autoScales = true
        return pdfView
    }

    func updateUIView(_ uiView: UIViewType, context: Context) {
        print("update view called")
        pdfView.document = pdfDocument
    }
}

Question: Can anyone shed any light as to why accessing this environment varible appears to be stopping the childview (pdfviewer) from appearing in the main view? I know that PDFViewer is being initalised because I still get update calls when it receives data.

My plan is to use the presentationMode to pop the view programmatically.

Thanks in advance.


Solution

  • Try to change PDFViewer as follows

    struct PDFViewer: UIViewRepresentable {
    
        @Binding var pdfDocument: PDFDocument
    
        func makeUIView(context: Context) -> PDFView {
            let pdfView = PDFView()
            pdfView.document = pdfDocument
            pdfView.autoScales = true
            return pdfView
        }
    
        func updateUIView(_ uiView: PDFView, context: Context) {
            print("update view called")
            uiView.document = pdfDocument
        }
    }