Search code examples
iosswiftpdfpdfkit

"Cannot assign value of type 'Void' to type 'PDFAction?'" error when setting an action for a PDFAnnotation


In my PDF Viewer app, I successfully opened a PDF and displayed all of its content. The PDF the app will always display is quite large with 130 pages. In the second page of the PDF, there is a table of contents. I want to add a PDFButton to the text and scroll to the correct page in the PDF the user has selected.

My current code displays a button, but the action I want the button to perform results in an error:

Cannot assign value of type 'Void' to type 'PDFAction?'

Here is the code I have tried:

func insertResetButtonInto(_ page: PDFPage, GoTo: PDFPage) {
    let resetButtonBounds = CGRect(x: 90, y: 200, width: 200, height: 15)
    let resetButton = PDFAnnotation(bounds: resetButtonBounds, forType: PDFAnnotationSubtype(rawValue: PDFAnnotationSubtype.widget.rawValue), withProperties: nil)
    resetButton.widgetFieldType = PDFAnnotationWidgetSubtype(rawValue: PDFAnnotationWidgetSubtype.button.rawValue)
    resetButton.widgetControlType = .pushButtonControl
    resetButton.backgroundColor = UIColor.green
    page.addAnnotation(resetButton)

    // Create PDFActionResetForm action to clear form fields.
    resetButton.action = pdfView.go(to: page)
}

How can I create a button in the PDF that works as a sequence or a scrolling function that takes the user to a different page in the same PDF document?


Solution

  • You are trying to assign a function to a variable which expects a PDFAction. Replace the line that throws the error with the following:

    resetButton.action = PDFActionGoTo(destination: PDFDestination(page: page, at: .zero))
    

    This passes a PDFDestination with the page you've initialized earlier to the PDFActionGoTo(destination:) initializer.

    If you want to modify the point of the destination, change the at parameter of the PDFDestination initializer to another CGPoint value:

    let point = CGPoint(x: 50, y: 100)
    resetButton.action = PDFActionGoTo(destination: PDFDestination(page: page, at: point))