Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect scrolling to another page in PDF using PDFkit

I'm trying to add current page number so when the user scrolling to another page it will display for example 2 of 3 (if the pdf have 3 pages)

for now, I use this code

it will display always 1 of 3

I think PDFkit using UIScrollView so I need to reach to the ScrollView that way I could detect when scrolling to another page and then increase the current page number

I didn't find any way to reach to scrollview in PDFkit

 func showCurrentPageIndex(){

        guard let totalPages = pdfContainerView.document?.pageCount else {return}
        guard let currentPage = pdfContainerView.currentPage else {return}
        guard let currentPageRef = currentPage.pageRef else {return}

let pageIndex = currentPageRef.pageNumber

      totalPageNumbers.text = "\(totalPages)"
      currentPageIndex.text =  "\(pageIndex)"
    }
like image 697
Basil Avatar asked Jan 02 '23 04:01

Basil


1 Answers

Use a notification (PDFViewPageChanged).

import UIKit
import PDFKit

class ViewController: UIViewController, PDFViewDelegate {
    // MARK: - Variables
    var totalCount = Int()

    // MARK: - IBOutlet
    @IBOutlet weak var pdfView: PDFView!

    // MARK: - Life cycle
    override func viewDidLoad() {
        super.viewDidLoad()

        let filePath = "Some file document path"
        pdfView.document = getDocument(path: filePath)
        if let total = pdfView.document?.pageCount {
            totalCount = total
        }
        pdfView.backgroundColor = .lightGray
        pdfView.autoScales = true
        pdfView.displayMode = .singlePageContinuous
        pdfView.usePageViewController(true, withViewOptions: nil)
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)

        /* notification */
        NotificationCenter.default.addObserver (self, selector: #selector(handlePageChange), name: Notification.Name.PDFViewPageChanged, object: nil)
    }

    func getDocument(path: String) -> PDFDocument? {
        let pdfURL = URL(fileURLWithPath: filePath)
        let document = PDFDocument(url: pdfURL)
        return document
    }
}
like image 198
El Tomato Avatar answered Feb 05 '23 20:02

El Tomato