swift - 如何在 Swift 中使用 PDFkit 搜索 PDF

标签 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)

最佳答案

创建 SearchTableViewController View Controller :

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 中添加此协议(protocol):

SearchTableViewControllerDelegate

关于swift - 如何在 Swift 中使用 PDFkit 搜索 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50609526/

相关文章:

ios - UITableView 滚动后 UITableViewCell 自定义按钮图像显示不正确

swift - 无法通过 PDFKit 在 iOS 13 和 iPhones 11、XR 等上绘制图像注释

ios - Swift PDFKit : Inconsistent behaviour with PDFView. currentDestination 和 PDFView.go(到目的地:PDFDestination)

ios - UITableViewCell 对齐列以适应内容

ios - 如何使用 PDFKit 获取段落高度

uitapgesturerecognizer - 在 iOS 13 中为 PDFView 添加点击手势识别器

ios - 将 pdf 文档保存到 iOS 文件应用程序时如何指定文件名?

ios - 钥匙串(keychain)返回零

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

ios - 当我在 Xcode 的界面生成器中做某事时,幕后会发生什么?