Search code examples
iosswiftscrolluiscrollviewpdfkit

iOS PDFKit Disable vertical scroll bounce


How does one disable scroll bounce in a PDFView using PDFKit?

The view where the PDF is shown doesn't have a scroll bounce option.

Here's my code:

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.autoScales = true
        pdfView.displaysPageBreaks = true
        pdfView.displayDirection = .vertical
        pdfView.displayMode = .singlePageContinuous
        pdfView.document = pdfDocument

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

Thanks in advance (for what is likely a ridiculously simple question!)


Solution

  • Unfortunately, there isn't an exported API to set the PDFView desired bouncing behavior.

    Having said that, you can (safely) exploit a PDFView implementation detail to hack your way around it for now:

    extension PDFView {
    
        /// Disables the PDFView default bouncing behavior.
        func disableBouncing() {
            for subview in subviews {
                if let scrollView = subview as? UIScrollView {
                    scrollView.bounces = false
                    return
                }
            }
            print("PDFView.disableBouncing: FAILED!")
        }
    }
    
    

    and then use it like this in your code:

    pdfView.disableBouncing()
    

    Caveat. Please keep in mind that such solution might break in future iOS releases. Nevertheless, rest assured your app won't crash as a result (you only won't be disabling the bouncing behavior at all).