Swift PDFKit handle annotation widget change?

424 views Asked by At

Is it possible to handle on change in swift pdf annotations? I would like to highlight the fields that need to be filled and then unhighlight when they have been filled.

pdfView.document = PDFDocument(url: url!)
    for index in 0..<pdfView.document!.pageCount{
        if let page = pdfView.document?.page(at: index){
            let annotations = page.annotations
            for annotation in annotations{
                print("Annotation Name :: \(annotation.fieldName ?? "")")
                annotation.backgroundColor = .opaqueSeparator
                switch annotation.fieldName {
                case "Customer":
                    annotation.widgetStringValue = "Customer"
                    annotation.backgroundColor = .tertiarySystemFill
                case "Customer Email":
                    annotation.widgetStringValue = "Customer Email"
                    annotation.backgroundColor = .tertiarySystemFill
                default:
                    annotation.widgetStringValue = ""
                }
                annotation.onChanged{ value in
                    annotation.backgroundColor = .opaqueSeparator
                }
            }
        }
    }

Annotations do not have a onChange or onChanged, what is the best way to go about this.

Thanks for any help!!

1

There are 1 answers

0
micah On

I haven't found a way to handle onchange on the PDFKit annotations, so I've just used a submit button that can control annotation highlighting by looping over all the annotations.

Button(action: {
    for index in 0..<pdfView.document!.pageCount{
        if let page = pdfView.document?.page(at: index){
            let annotations = page.annotations
            for annotation in annotations{
                print("Annotation Name :: \(annotation.fieldName ?? "")")
                annotation.backgroundColor = .opaqueSeparator
                switch annotation.fieldName {
                case "Customer":
                    annotation.widgetStringValue = "Customer"
                    annotation.backgroundColor = .tertiarySystemFill
                case "Customer Email":
                    annotation.widgetStringValue = "Customer Email"
                    annotation.backgroundColor = .tertiarySystemFill
                default:
                    annotation.widgetStringValue = ""
                }
                annotation.onChanged{ value in
                    annotation.backgroundColor = .opaqueSeparator
                }
            }
        }
    }
},
label: {
    Text("Submit")
        .frame(width: 180, height: 50, alignment: .center)
        .background(Color.blue)
        .foregroundColor(.white)
        .cornerRadius(10)
})