squarehippo10
squarehippo10

Reputation: 1945

SwiftUI - Value of protocol type 'Any' cannot conform to 'View'

I'm trying to convert an array of SwiftUI views into a PDF. I think I just about have it, except for one small problem - the array type. I can't get the views into an array that PDFKit will recognize. In the code below, if I replace

let tempView = UIHostingController(rootView: view)

with

let tempView = UIHostingController(rootView: PageOne())   

the code below works great. But when I try to put PageOne() into an array of type Any I get the error, "Value of protocol type 'Any' cannot conform to 'View'; only struct/enum/class types can conform to protocols" Which makes sense. But what I don't get is how I should be doing it.

var viewsToConvert = [Any]()
viewsToConvert.append(PageOne())
viewsToConvert.append(PageTwo())

let pdfData = NSMutableData()
let pdfPageFrame = CGRect(x: 0, y: 0, width: width, height: height)
UIGraphicsBeginPDFContextToData(pdfData, pdfPageFrame, nil)
let graphicsContext = UIGraphicsGetCurrentContext()
for view in viewsToConvert {
   let tempView = UIHostingController(rootView: view)
   tempView.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
            
   UIGraphicsBeginPDFPage()
   tempView.view.layer.render(in: graphicsContext!)
            
   tempView.removeFromParent()
   tempView.view.removeFromSuperview()
}
UIGraphicsEndPDFContext()

return saveViewPdf(data: pdfData, fileName: "Quote")
}

Upvotes: 2

Views: 590

Answers (1)

pawello2222
pawello2222

Reputation: 54651

You need to use AnyView instead of Any:

var viewsToConvert = [AnyView]()
viewsToConvert.append(AnyView(PageOne()))
viewsToConvert.append(AnyView(PageTwo()))

Upvotes: 3

Related Questions