iOS PDFKit: make Text Widget PDFAnnotation readonly

心不动则不痛 提交于 2019-12-10 19:08:57

问题


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)
            }
        }

    }
}


来源:https://stackoverflow.com/questions/49941644/ios-pdfkit-make-text-widget-pdfannotation-readonly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!