ios - PDFKit 交换注释内容

标签 ios swift apple-pdfkit

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

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

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

最佳答案

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

关于ios - PDFKit 交换注释内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51488591/

相关文章:

ios - 使用 Swift 5 - PDFKit 在 iOS 中编辑和保存现有的 pdf 文档

ios - UITableView 应用程序在 cellForRow 委托(delegate)方法调用上崩溃

ios - 如何从 viewController 访问 Swift 3 中的另一个 viewController

ios - Swift 在代码中将方向设置为特定屏幕

ios - 有没有办法在Box2D中绘制凹多边形并检测与其他形状的碰撞

ios - 使用 UIGraphicsPDFRenderer 创建 PDF 时添加像 "page x of y"这样的页脚

storyboard - 我可以在 iOS 11 中通过 Storyboard 添加 PDFView

iphone - 如何制作可在 iOS 5 至 7 上运行的 armv7 arm64 fat 二进制文件?

ios - 使用XCode构建Sqlite ICU

ios - Swift 4 中 [MoveCommand] 的替代品是什么