如何在Swift中使用PDFkit搜索PDF

时间:2018-05-30 16:28:19

标签: swift ios-pdfkit

我的目标是搜索字符串,然后转到它。我有这三行代码来实现它。我只是知道我的想法过程是因为错过了什么。我不确定如何使用.findstring。我读到它返回一个PDFSelections数组。但我不知道如何使用它来使用PDFSelection数组.setCurrentSelection

let found = document.findString(selection, withOptions: .caseInsensitive)
let stringSelection = page?.selection(for: NSRange(location:10, length:5))
pdfView.setCurrentSelection(stringSelection, animate: true)

2 个答案:

答案 0 :(得分:1)

我认为您可以使用

到达当前选择
pdfView.go(to selection: pdView.currentSelection)

根据此文档,可以使用选择,目标和文本来导航PDF https://developer.apple.com/documentation/pdfkit/pdfview/1505172-go

答案 1 :(得分:0)

创建SearchTableViewController ViewController:

import UIKit
import PDFKit

protocol SearchTableViewControllerDelegate: class {
    func searchTableViewController(_ searchTableViewController: SearchTableViewController, didSelectSerchResult selection: PDFSelection)
}

class SearchTableViewController: UITableViewController {

    open var pdfDocument: PDFDocument?
    weak var delegate: SearchTableViewControllerDelegate?

    var searchBar = UISearchBar()
    var searchResults = [PDFSelection]()

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.rowHeight = 150

        searchBar.delegate = self
        searchBar.showsCancelButton = true
        searchBar.searchBarStyle = .minimal
        navigationItem.titleView = searchBar

        navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel,
                                                           target: self,
                                                           action: #selector(closeBtnClick))

        tableView.register(UINib(nibName: "SearchViewCell", bundle: nil), forCellReuseIdentifier: "SearchViewCell")

    }

    @objc func closeBtnClick(sender: UIBarButtonItem) {
        dismiss(animated: false, completion: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        searchBar.becomeFirstResponder()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source
    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return searchResults.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SearchViewCell", for: indexPath) as! SearchViewCell

        let selection = searchResults[indexPath.row]
        let page = selection.pages[0]
        let outline = pdfDocument?.outlineItem(for: selection)

        let outlintstr = outline?.label ?? ""
        let pagestr = page.label ?? ""
        let txt = outlintstr + " 页码:  " + pagestr
        cell.destinationLabel.text = ""

        let extendSelection = selection.copy() as! PDFSelection
        extendSelection.extend(atStart: 10)
        extendSelection.extend(atEnd: 90)
        extendSelection.extendForLineBoundaries()

        let range = (extendSelection.string! as NSString).range(of: selection.string!, options: .caseInsensitive)
        let attrstr = NSMutableAttributedString(string: extendSelection.string!)
        attrstr.addAttribute(NSAttributedStringKey.backgroundColor, value: UIColor.yellow, range: range)

        cell.resultTextLabel.attributedText = attrstr

        return cell
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        let selection = searchResults[indexPath.row]
        delegate?.searchTableViewController(self, didSelectSerchResult: selection)
        dismiss(animated: false, completion: nil)
    }

    override func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        searchBar.resignFirstResponder()
    }
}

extension SearchTableViewController: UISearchBarDelegate {
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
    }

    func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
        pdfDocument?.cancelFindString()
        dismiss(animated: false, completion: nil)
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//        if searchText.count < 2 {
//            return
//        }

        searchResults.removeAll()
        tableView.reloadData()
        pdfDocument?.cancelFindString()
        pdfDocument?.delegate = self
        pdfDocument?.beginFindString(searchText, withOptions: .caseInsensitive)
    }
}

extension SearchTableViewController: PDFDocumentDelegate {
    func didMatchString(_ instance: PDFSelection) {
        searchResults.append(instance)
        tableView.reloadData()
    }
}

在搜索按钮上点击:

let searchViewController = SearchTableViewController()
        searchViewController.pdfDocument = self.pdfdocument
        searchViewController.delegate = self

        let nav = UINavigationController(rootViewController: searchViewController)
        self.present(nav, animated: false, completion:nil)

您将在以下位置看到突出显示的文本:

func searchTableViewController(_ searchTableViewController: SearchTableViewController, didSelectSerchResult selection: PDFSelection) {
        selection.color = UIColor.yellow
        self.pdfview.currentSelection = selection
        self.pdfview.go(to: selection)
        calculateStandByMood()
    }

只需在pdfViewController中添加此协议:

SearchTableViewControllerDelegate