UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SwiftUI UIViewRepresentable PDFKit PDFView AttributeGraph: cycle detected through attribute xxx

Forums > SwiftUI

I have created a minimalistic example project at GitHub: https://github.com/Harold-D/PDFView_Representable illustrating the problem.

I have wrapped an PDFKit.PDFView in a UIViewRepresentable. It works correctly but, when setting the PDF in updateUIView(), I get a lot of

AttributeGraph: cycle detected through attribute xxx

errors.

This drives me crazy because I cannot figure out why. Help is much appreciated.

struct MyPDFView: UIViewRepresentable {
    typealias UIViewType = PDFView
    @State var pdf: Data

    func makeUIView(context: UIViewRepresentableContext<MyPDFView>) -> UIViewType {
        return PDFView()
    }

    func updateUIView(_ view: UIViewType, context: UIViewRepresentableContext<MyPDFView>) {
        debugPrint("update view")
        view.document = PDFDocument(data: pdf)

    }
}

struct ContentView: View {
    @State var togglePDF = true

    var body: some View {
        VStack {
            Button {
                togglePDF.toggle()
            } label: {
                Text("Change PDF")
                    .padding()
                    .foregroundColor(.white)
                    .background(Color.blue)
                    .cornerRadius(15)
            }
            MyPDFView(pdf: loadPDFAsData(togglePDF: togglePDF))
        }
    }

    private func loadPDFAsData(togglePDF: Bool) -> Data{
        let fileName = (togglePDF ? "1" : "2")

        guard let pdfURL = Bundle.main.url(forResource: fileName, withExtension: "pdf") else {
            fatalError("Could not find PDF")
        }

        do {
            return try Data(contentsOf: pdfURL)
        } catch {
            fatalError("Could not load PDF")
        }
    }
}

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.