iOS PDFKit not filling UIView

I have been struggling with a similar issue, and very weird and inconsistent behavior of autoScales. In my case, the automatic scaling worked either on the first loaded document, but not on any subsequent loaded documents in the same pdfView, or it only worked from the second loaded document.

I have embedded the pdfView in a UIScrollView, in order to gain more control over the gesture behavior.

The ordering of the commands seems to indeed be key. After a lot of trial and error, this is the order that worked for me best:

  1. Load the document

    pdfView.document = pdfDocument

  2. Set the display mode

    pdfView.displayMode = .singlePage

  3. Set any constraints, background, shadow etc.

  4. Perform changes to the pdfView size by modifying constraints

  5. Set autoScales

    pdfView.autoScales = true

  6. Set the scale factors

    pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit

This is the only order in which everything worked in my case, and it only worked when stages 2, 5 and 6 were all present.


Right, firstly many thanks to Mahesh. While his answer didn't directly answer my question, two things they said did provide a route to solving this.

Overall to set the pdf to fill the view, I needed to set autoresizing and autoscales BEFORE

pdfView.document = pdfDocument

And to then control the zoom, set these AFTER

pdfView.document = pdfDocument

Thus my final code is:

func pdfDisplay() {

    if let path = Bundle.main.path(forResource: pdfObject, ofType: "pdf") {
        let url = URL(fileURLWithPath: path)
        if let pdfDocument = PDFDocument(url: url) {

            pdfView.autoresizesSubviews = true
            pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight, .flexibleTopMargin, .flexibleLeftMargin]
            pdfView.displayDirection = .vertical

            pdfView.autoScales = true
            pdfView.displayMode = .singlePageContinuous
            pdfView.displaysPageBreaks = true
            pdfView.document = pdfDocument

            pdfView.maxScaleFactor = 4.0
            pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit

        }
    } 
}

Not going to lie, I'm not sure why this works in this order, I would appreciate a comment from a wiser mind than mine but I hope this helps others