如何使用PDFkit检测滚动到PDF的另一页

时间:2019-03-17 11:58:45

标签: swift uiscrollview pdfkit

我正在尝试添加当前页码 因此,当用户滚动到另一页时,它将显示 例如 2之3(如果pdf有3页)

现在,我使用此代码

它将始终显示3之1

我认为使用UIScrollView的PDFkit 所以我需要以那种可以检测到滚动到另一页然后增加当前页数的方式到达ScrollView

我在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)"
    }

1 个答案:

答案 0 :(得分:1)

使用通知(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
    }
}