Skip to content

Instantly share code, notes, and snippets.

@onevcat
Created December 19, 2018 05:15
Show Gist options
  • Save onevcat/16d23100ab34fb2f1e6b9d0642c9d592 to your computer and use it in GitHub Desktop.
Save onevcat/16d23100ab34fb2f1e6b9d0642c9d592 to your computer and use it in GitHub Desktop.
import UIKit
import WebKit
// Disableing `WKWebView` user zooming by returning `nil` in `UIScrollViewDelegate`'s
// `viewForZooming` delegate method.
// On iOS 12, the delegate method only called when set the web view itself as the
// scroll view delegate.
class WebView: WKWebView {}
extension WebView: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return nil
}
}
class ViewController: UIViewController {
var webView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .red
webView = WebView(frame: .zero)
// This does not work on iOS 12.
// `viewForZooming` in "extension ViewController" not called at all.
// But on iOS 11 and earlier, it works fine.
// webView.scrollView.delegate = self
// Only this works on iOS 12!
webView.scrollView.delegate = webView
webView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(webView)
let safeAreaLayoutGuide = view.safeAreaLayoutGuide
[
webView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor),
webView.leadingAnchor.constraint(equalTo: safeAreaLayoutGuide.leadingAnchor),
webView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor),
webView.trailingAnchor.constraint(equalTo: safeAreaLayoutGuide.trailingAnchor)
]
.forEach { $0.isActive = true }
webView.load(URLRequest(url: URL(string: "https://google.com")!))
}
}
extension ViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return nil
}
}
@bkbeachlabs
Copy link

Note: this appears to work, even if you don't set the webView as the scrollView's delegate. This tells us it already is the scrollView's delegate.

So this is a bit of magic, but it works :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment