PDFKit交换注释内容

时间:2018-07-23 23:46:45

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

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

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

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

2 个答案:

答案 0 :(得分:0)

我建议您使用经典的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 updating annotation position

也许当您更改注解内容时,Apple会找到一种在屏幕上更新PDFView的方法。

答案 1 :(得分:0)

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