Created
December 19, 2018 05:15
-
-
Save onevcat/16d23100ab34fb2f1e6b9d0642c9d592 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
it's helpful
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
1> delegate = self
iOS 11 and earlier call webview for viewForZoom and self for viewForZoom
iOS 12 and later called webview for viewForZoom
2> delegate = webView
all only calle webview for viewForZoom