访问 @Environment(\.presentationMode) 阻止 PDFView 出现

问题描述

问题: 访问 @Environment(.presentationMode) 会阻止显示我的 PDFView。

工作代码:在 MainView 中通过 PDFViewer 显示 pdf 文档

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:不显示文档或 PDFViewer(唯一的变化是访问@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
    }
}

问题: 任何人都可以解释为什么访问此环境变量似乎会阻止子视图 (pdfviewer) 出现在主视图中?我知道 PDFViewer 正在初始化,因为在它接收数据时我仍然会收到更新调用。

我的计划是使用presentationMode以编程方式弹出视图。

提前致谢。

解决方法

尝试将PDFViewer改成如下

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
    }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...