fl0*_*034 0 pdfkit pdfview ios swift
我正在尝试PDFView,并希望突出显示搜索到的单词。我在这里关注这个小教程(请参阅搜索段落)。
我正在为我的PDF找到匹配项,但是当我设置时pdfView.highlightedSelections = searchedItems什么也没发生。
这是我的代码(VC扩展了PDFDocumentDelegate)
var document: PDFDocument!
var searchedItems: [PDFSelection] = []
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "test3", withExtension: "pdf")
document = PDFDocument(url: url!)
pdfView.document = document
pdfView.document?.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
pdfView.document?.findString("Product", withOptions: .caseInsensitive)
}
func documentDidEndDocumentFind(_ notification: Notification) {
pdfView.highlightedSelections = nil
pdfView.highlightedSelections = searchedItems
}
func documentDidFindMatch(_ notification: Notification) {
if let selection = notification.userInfo?.first?.value as? PDFSelection {
selection.color = .yellow
searchedItems.append(selection)
print("didFindMatch")
}
}
Run Code Online (Sandbox Code Playgroud)
好的,我通过在这里阅读以下主题来自己弄清楚:https : //forums.developer.apple.com/thread/93414
似乎highlightedSelections无法按文档所述。我将向Apple提交错误。
PDFSelection本身具有Type的内部数组PDFSelection。有了这个,我可以在其中添加多个选择。之后,我可以pdfView.setCurrentSelection(_:animate:)用来设置此嵌套选择数组。
var document: PDFDocument!
var searchedItem: PDFSelection?
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "test3", withExtension: "pdf")
document = PDFDocument(url: url!)
pdfView.document = document
pdfView.document?.delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.document?.beginFindString("Product", withOptions: .caseInsensitive)
}
func documentDidEndDocumentFind(_ notification: Notification) {
pdfView.setCurrentSelection(searchedItem, animate: true)
}
func documentDidFindMatch(_ notification: Notification) {
if let selection = notification.userInfo?.first?.value as? PDFSelection {
selection.color = .yellow
if searchedItem == nil {
// The first found item sets the object.
searchedItem = selection
} else {
// All other found selection will be nested
searchedItem!.add(selection)
}
}
}
Run Code Online (Sandbox Code Playgroud)
扩展拉法尔的答案,我让它甚至可以处理多个页面文档(和多个搜索词),就像这样。我还无法测试的是这是否适用于跨多个页面的术语:
private func highlight(searchTerms: [String]?)
{
searchTerms?.forEach { term in
let selections = pdfView?.document?.findString(term, withOptions: [.caseInsensitive])
selections?.forEach { selection in
selection.pages.forEach { page in
let highlight = PDFAnnotation(bounds: selection.bounds(for: page), forType: .highlight, withProperties: nil)
highlight.endLineStyle = .square
highlight.color = UIColor.orange.withAlphaComponent(0.5)
page.addAnnotation(highlight)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1382 次 |
| 最近记录: |