9

可以在不删除注释/构建新注释的情况下在 PDFKit 中更改注释的文本(即contents)吗?FreeText

在 a 中查看时,以下代码段不会更改注释的内容PDFView

let url = Bundle.main.url(forResource: "Test", withExtension: "pdf")!
let document = PDFDocument(url: url)!

for index in 0..<document.pageCount {
    let page: PDFPage = document.page(at: index)!
    let annotations = page.annotations
    for annotation in annotations {
        annotation.contents = "[REPLACED]"
    }
}
mainPDFView.document = document

这可行 - 但需要替换注释(因此必须复制注释的所有其他细节):

let url = Bundle.main.url(forResource: "Test", withExtension: "pdf")!
let document = PDFDocument(url: url)!

for index in 0..<document.pageCount {
    let page: PDFPage = document.page(at: index)!
    let annotations = page.annotations
    for annotation in annotations {
        print(annotation)
        page.removeAnnotation(annotation)
        let replacement = PDFAnnotation(bounds: annotation.bounds,
                                        forType: .freeText,
                                        withProperties: nil)

        replacement.contents = "[REPLACED]"
        page.addAnnotation(replacement)
    }
}

mainPDFView.document = document

注意:添加/删除相同的注释也无济于事。

4

2 回答 2

2

我建议您使用经典的 for 循环遍历注释数组并找到要修改的注释的索引,然后下标数组应该“就地”修改注释。

这是一个修改所有注释的示例:

let url = Bundle.main.url(forResource: "Test", withExtension: "pdf")!
let document = PDFDocument(url: url)!

for index1 in 0..<document.pageCount {
    let page: PDFPage = document.page(at: index)!
    let annotations = page.annotations
    for index2 in 0..<annotations.count {
        annotations[index2].contents = "[REPLACED]"
    }
}

阅读有关变异数组的内容:http: //kelan.io/2016/mutating-arrays-of-structs-in-swift/

希望有帮助,加油!

LE:实际上是一个错误,请看这个:iOS 11 PDFKit not updates annotation position

当您很快更改注释的内容时,Apple 可能会找到一种方法来更新屏幕上的 PDFView。

于 2018-07-26T23:08:50.893 回答
0

您是否尝试pdfView.annotationsChanged(on: pdfPage)在更新注释文本后调用?

于 2018-08-03T15:15:50.227 回答