PDFKit交换注释内容

Kev*_*tre 9 ios swift apple-pdfkit

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

在以下位置查看时,以下代码段不会更改注释的内容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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

注意:添加/删除相同的注释也没有用.

Mih*_*rős 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]"
    }
}
Run Code Online (Sandbox Code Playgroud)

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

希望有帮助,加油!

LE:这实际上是一个错误,请参阅这个:iOS 11 PDFKit not update annotationposition

当您更改注释内容时,也许苹果很快就会找到一种方法来更新屏幕上的 PDFView。

  • 注意:看起来这是 Pranav 确认的 SDK 的一个错误。授予赏金以确保它不会浪费...... (2认同)