I would like to make the Text Widget PDFAnnotation readonly. I tried to set the isReadOnly flag to true, but it doesn't seem to make any difference. The user is still able to edit the annotation after tapping it.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
It seems to be a bug/oversight that PDFKit doesn't honor the isReadOnly attribute on annotations. However I was able to work around this by adding a blank annotation over other annotations in the document. I added a makeReadOnly() extension to PDF document that does this for all annotations to make the whole document read only. Here's the code:
// A blank annotation that does nothing except serve to block user input
class BlockInputAnnotation: PDFAnnotation {
init(forBounds bounds: CGRect, withProperties properties: [AnyHashable : Any]?) {
super.init(bounds: bounds, forType: PDFAnnotationSubtype.stamp, withProperties: properties)
self.fieldName = "blockInput"
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func draw(with box: PDFDisplayBox, in context: CGContext) {
}
}
extension PDFDocument {
func makeReadOnly() {
for pageNumber in 0..<self.pageCount {
guard let page = self.page(at: pageNumber) else {
continue
}
for annotation in page.annotations {
annotation.isReadOnly = true // This _should_ be enough, but PDFKit doesn't recognize the isReadOnly attribute
// So we add a blank annotation on top of the annotation, and it will capture touch/mouse events
let blockAnnotation = BlockInputAnnotation(forBounds: annotation.bounds, withProperties: nil)
blockAnnotation.isReadOnly = true
page.addAnnotation(blockAnnotation)
}
}
}
}