Fabian Boulegue
Fabian Boulegue

Reputation: 6608

Draw above UIWebView in Swift

I'm looking for a way to draw "Lines" above a UIWebView.

I have a UIWebView that display a PDF file, the user should be able to add "Lines" and "Sketches" (simple one color lines etc) for sure this could be done with a UIView on top of the UIWebView but i m running into 2 logical problems.

First can the UIView where the drawing is, be transparent beside the lines - so you can view the pdf through it?

How could i handle the zooming in the PDF, if a user zoom the WebView, the UIView have to zoom "with each other" - so the drawing stays at the same spot/zoom level?

Is there any other way to display a PDF and add drawings/annotations to it? Currently i m using a QLPreviewController where i see no way to add any kind of annotations?

Is three any best practice for this?

Upvotes: 1

Views: 681

Answers (1)

Rob Napier
Rob Napier

Reputation: 299275

PSPDFKit handles this (and many other hard PDF problems) very well. Using a web view for this kind of problem is likely to have many little corner cases. Any commercial product that has non-trivial needs around PDFs should definitely start there. For open source projects I don't have a great answer beyond "yeah, PDFs are a pretty tough; good luck."

That said, here are some starting points that may help you.

  • You can turn off zooming with webView.scalesPageToFit = false
  • You can get the current zoom scale using webView.scrollView.zoomScale
  • I believe you can KVO observe zoomScale to track it while it changes, but you may only get the target value (which will cause you to lag).
  • You can disable zooming (scalesPageToFit) and then re-implement it yourself with a UIPinchGestureRecognizer and scrollView.setZoomScale(_:animated:). That way you could track the zoom changes better. You could also try to handle the animation yourself with a CABasicAnimation so that you could keep it in sync.

My experience with scroll views, web views, and PDF is that there are a lot of little funny interactions that will surprise you. Getting something that "kind of" works isn't that hard, but getting it really clean, smooth, and beautiful can be a nightmare. That's why I typically recommend PSPDFKit to clients. You'll generally spend much less on the license than on the custom development.

Upvotes: 3

Related Questions