【问题标题】:PDFKit Swapping Content of AnnotationPDFKit 交换注释的内容
【发布时间】:2018-12-31 11:37:02
【问题描述】:

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

PDFView 中查看时,以下 sn-p 不会更改注释的内容:

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

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

【问题讨论】:

  • developer.apple.com/documentation/pdfkit/pdfannotation/… ,它有一个函数setContent,试试看!
  • 在开发人员文档中,您引用的 setContents 只是 getter / setter contents。我的例子就是使用它。
  • 我无法重现您的问题,因为第一个代码 sn-p 对我有用:将已创建的注释替换为已替换的内容。
  • 您可能需要检查页面的注释确实都是.freeText 否则更改contents 变量不会改变任何东西。
  • @PranavKasetti 确认它是.freeText。您是在 iOS 还是 Mac 上运行的示例?

标签: ios swift apple-pdfkit


【解决方案1】:

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

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

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:其实是个bug,看这个:iOS 11 PDFKit not updating annotation position

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

【讨论】:

  • 我认为这没有帮助。注解不是值类型(类)。我还认为编译器会警告类似“不能分配给'让'常量属性......”或者如果是这种情况......
  • 我更新了我的答案,因为我开始尝试你的确切情况,因为你是对的。测试了你的,它工作正常 - 就改变 PDFAnnotation 对象的内容属性而言 - 你的问题实际上是你的 PDFView (在屏幕上)没有刷新,你没有看到你的更改,我现在明白了,但是发生了变化..这是一个错误,在我看来很简单。
  • 我认为您的另一点也不是问题所在。在更改注释之前,我不会将文档添加到 PDFView。
  • 你还有什么问题?
  • 注意:这似乎是 Pranav 确认的 SDK 的错误。授予赏金以确保它不会浪费......
【解决方案2】:

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

【讨论】:

  • 是的 - 这发生在将文档添加到页面之前。
猜你喜欢
  • 1970-01-01
  • 2015-01-21
  • 1970-01-01
  • 2019-01-07
  • 2018-08-06
  • 1970-01-01
  • 2022-01-28
  • 2021-07-23
  • 2014-08-14
相关资源
最近更新 更多