3

My goal is to search for a string and then go to it. I have these three lines of code needed to implement it. I just know my thought process for getting there is missing something. I am not sure how to use .findstring. I read that it returns an array of PDFSelections. But I am not sure how to use that to use .setCurrentSelection using the PDFSelection array.

let found = document.findString(selection, withOptions: .caseInsensitive)
let stringSelection = page?.selection(for: NSRange(location:10, length:5))
pdfView.setCurrentSelection(stringSelection, animate: true)
rmaddy
  • 314,917
  • 42
  • 532
  • 579
mrwadepro
  • 229
  • 1
  • 6
  • 16
  • I've never used `PDFKit` so this is a guess, but I think `selection` actually highlights some text on the page. What you probably want to use is `pdfView.go(to: PDFDestination(...))` Although how you're going to get that destination might be difficult. – Guy Kogus May 30 '18 at 22:05

2 Answers2

5

Create 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()
    }
}

On Search Button Tap :

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

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

You will get highlighted text in :

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

Just add this protocol in pdfViewController :

SearchTableViewControllerDelegate
Mahesh Shahane
  • 489
  • 5
  • 16
3

I think you can reach to the current selection using

pdfView.go(to selection: pdView.currentSelection)

According to this doc, PDF can be navigated using selection, destination and rect https://developer.apple.com/documentation/pdfkit/pdfview/1505172-go

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Kirty07
  • 53
  • 4