If you're loading a PDF and want a background color different than the standard gray, it seems that it is necessary to wait until the document is loaded, then clear the backgrounds of the subviews. The advantage of using a WKWebView
over a PDFView
(iOS 11+) is that WKWebView
s have double-tap to zoom and a page count indicator built in, and are compatible with older versions of iOS.
It should be noted that it's not a great practice to dig into system views like this as Apple can change the implementation at any time, potentially breaking the solution.
Here is how I implemented a PDF preview controller with a black background in Swift 4:
class SomeViewController: UIViewController {
var observer: NSKeyValueObservation?
var url: URL
init(url: URL) {
self.url = url
super.init(nibName: nil, bundle: nil)
}
func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.black
let webView = WKWebView()
webView.translatesAutoResizingMaskIntoConstraints = false
self.view.addSubview(webView)
NSLayoutConstraint.activate([
webView.topAnchor.constraint(equalTo: self.view.topAnchor),
webView.leftAnchor.constraint(equalTo: self.view.leftAnchor),
webView.rightAnchor.constraint(equalTo: self.view.rightAnchor),
webView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
])
self.observer = webView.observe(\.isLoading, changeHandler: { (webView, change) in
webView.clearBackgrounds()
})
webView.loadFileURL(self.url, allowingReadAccessTo: self.url)
}
}
extension UIView {
func clearBackgrounds() {
self.backgroundColor = UIColor.clear
for subview in self.subviews {
subview.clearBackgrounds()
}
}
}