ios-在WKWebVi中禁用放大手势

我正在寻找一种方法来禁用WKWebView的iOS实现上的“缩小缩放”放大手势。 OS X有一个可用的放大BOOL属性,但在iOS上似乎不可用。

WKWebView.h

#if !TARGET_OS_IPHONE
/* @abstract A Boolean value indicating whether magnify gestures will
 change the web view's magnification.
 @discussion It is possible to set the magnification property even if
 allowsMagnification is set to NO.
 The default value is NO.
 */
@property (nonatomic) BOOL allowsMagnification;

我也尝试查看WKWebView的手势识别器,但这似乎是在清空一个空数组。 我假设实际的识别器深入到组件的结构中(从它的外观来看相当复杂),并且如果可能的话,宁愿不去挖掘它们。

我知道可能会破坏手势的潜在黑客(选择性地将手势传递到WebView,添加子视图以捕获捏合手势等),但是我一直发现这些漏洞会导致事件延迟,并且希望将实现保留为 清洁/黑客免费。

Kevin asked 2019-11-19T04:16:18Z
20个解决方案
75 votes

您可以通过设置WKWebKit的UIScrollView的委托并实现viewForZooming(in:)来阻止用户缩放,如下所示:

class MyClass {
    let webView = WKWebView()

    init() {
        super.init()
        webView.scrollView.delegate = self
    }

    deinit() {
        // Without this, it'll crash when your MyClass instance is deinit'd
        webView.scrollView.delegate = nil
    }
}

extension MyClass: UIScrollViewDelegate {
    func viewForZooming(in scrollView: UIScrollView) -> UIView? {
        return nil
    }
}
Landschaft answered 2019-11-19T04:16:29Z
42 votes

以下答案不再适用于iOS 10 Beta。

为了提高Safari中网站的可访问性,用户现在可以   即使网站在设置中将user-scalable = no设置为“无”,也可以缩小缩放   视口。


WKWebView似乎像Mobile Safari一样尊重视口元标记(这是可以预期的)。 因此,我发现在页面加载后通过JavaScript将该标签注入DOM可以解决问题。 除非您确切知道将什么HTML加载到Web视图中,否则我将对此解决方案感到厌倦,否则我怀疑它会带来意想不到的后果。 就我而言,我正在加载HTML字符串,因此我可以将其添加到应用程序附带的HTML中。

通用地对任何网页执行此操作:

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    NSString *javascript = @"var meta = document.createElement('meta');meta.setAttribute('name', 'viewport');meta.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no');document.getElementsByTagName('head')[0].appendChild(meta);";

    [webView evaluateJavaScript:javascript completionHandler:nil];
}

看一下刚刚完成了哪种导航可能是明智的,因为只有新页面需要执行此javascript。

Kevin answered 2019-11-19T04:17:19Z
33 votes

我尝试将UIScrollViewminimumZoomScaleUIScrollView的属性设置为1619或isMultipleTouchEnabledUIView的属性设置为false或通过调用viewForZooming(in:)viewForZooming(in:)返回nil但没有任何作用。 在我的情况下,经过多次试验和错误,以下情况在我的情况下有效[在iOS 10.3上测试]:

class MyViewController: UIViewController {
   var webView: WKWebView?

   override viewDidLoad() {
      super.viewDidLoad()

      //...
      self.webView.scrollView.delegate = self
      //...
   }
}

extension MyViewController: UIScrollViewDelegate { 
   func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
      scrollView.pinchGestureRecognizer?.isEnabled = false
   }
}
yohannes answered 2019-11-19T04:17:46Z
16 votes

本地解决方案不适用于我,并且注入JS并不理想。 我注意到发生缩放并调用我的委托时,即使在初始化Webview时禁用了pinchGestureRecognizer,也可以启用它。 为了解决这个问题,每当缩放开始时,我将其设置为禁用:

extension ViewController: UIScrollViewDelegate {

    // disable zooming in webview
    func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
        scrollView.pinchGestureRecognizer?.isEnabled = false
    }
}
pulse4life answered 2019-11-19T04:18:15Z
14 votes

Landschaft的完整Swift 3 / iOS 10版本的答案:

import UIKit
import WebKit

class MyViewController: UIViewController, UIScrollViewDelegate {

    var webView = WKWebView()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.addSubview(webView)
        webView.scrollView.delegate = self
    }

    // Disable zooming in webView
    func viewForZooming(in: UIScrollView) -> UIView? {
        return nil;
    }
}
Simon Epskamp answered 2019-11-19T04:18:41Z
12 votes

完成工作代码以禁用Swift中的WkWebView缩放。

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate {
    var webView : WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        webView = WKWebView(frame: .zero, configuration:webConfiguration)
        webView.uiDelegate = self

        let source: String = "var meta = document.createElement('meta');" +
            "meta.name = 'viewport';" +
            "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';" +
            "var head = document.getElementsByTagName('head')[0];" + "head.appendChild(meta);";

        let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        webView.configuration.userContentController.addUserScript(script)

        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let myUrl = URL(string: "https://www.google.com")

        let myRequest = URLRequest(url: myUrl!)
        webView.load(myRequest)
    }
}
Gulshan Kumar answered 2019-11-19T04:19:06Z
4 votes

您可以为此使用UIScrollViewDelegate。 首先在viewDidLoad()或任何其他合适的方法中将委托分配给您的Web视图:

class LoginViewController: UIViewController, WKUIDelegate, UIScrollViewDelegate {
  override func viewDidLoad() {
  webView.scrollView.delegate = self 
  }

 //And add this delegate method in your controller: 

  func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
  scrollView.pinchGestureRecognizer?.isEnabled = false
  scrollView.panGestureRecognizer.isEnabled = false
  }
}
Yakup Ad answered 2019-11-19T04:19:33Z
4 votes

如果您显示本地html,则可以修改此html并将此meta标签放入html中:

<head>
<meta content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0' name='viewport' />
</head>
Leszek Szary answered 2019-11-19T04:19:59Z
3 votes

Swift 2.0

extension WKWebView {
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return nil
    }
}
quemeful answered 2019-11-19T04:20:21Z
2 votes

这就是我为仅一个webview的应用程序禁用Swift3视图控制器的缩放的方法

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate, UIScrollViewDelegate {

    @IBOutlet var webView: WKWebView!

    override func loadView() {
        webView = WKWebView()
        webView.navigationDelegate = self
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.scrollView.delegate = self
    }

    func viewForZooming(in: UIScrollView) -> UIView? {
        return nil;
    }    

}
godblessstrawberry answered 2019-11-19T04:20:46Z
1 votes

我的信誉不足,无法在评论中添加评论,但我想提一提凯文(Kevin)的解决方案(元视口)不再适用于iOS 10 Beta。 不过,Landschaft的解决方案对我有用!

由于JS解决方案使用W3C标准,因此应始终对其进行支持。

啊,凯文,我希望这是怎么回事。

此处更多:[https://stackoverflow.com/a/37859168/1389714]

mark answered 2019-11-19T04:21:31Z
1 votes

如果处理html内的链接对您来说并不重要(例如您只想显示文本),最简单的方法就是关闭用户交互webView.userInteractionEnabled = false

lvp answered 2019-11-19T04:21:57Z
1 votes

通过要求手势识别器失败,禁用双击以缩放手势。 用户双击时,它将阻止浏览器采取措施。

import UIKit

class DisableDoubleTapRecognizer : UITapGestureRecognizer, UIGestureRecognizerDelegate{
    override init(target: Any?, action: Selector?) {
        super.init(target: target, action: action)
    }
    
    init() {
        super.init(target:nil, action: nil)
        self.numberOfTapsRequired = 2;
        self.delegate = self;
    }
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true;
    }
}

//in your view controller
override func viewDidLoad() {
        super.viewDidLoad()
        
        webView.addGestureRecognizer(DisableDoubleTapRecognizer())
    }

user3543806 answered 2019-11-19T04:22:30Z
1 votes

一种防止缩放的简单方法

override func viewDidLoad() {
    super.viewDidLoad()

    webView.scrollView.delegate = self
}

func scrollViewDidZoom(_ scrollView: UIScrollView) {

    scrollView.setZoomScale(1.0, animated: false)
}
Waqar Ahmed answered 2019-11-19T04:22:56Z
0 votes

我们需要在XCode 8中使用以下签名更改委托调用:

覆盖func viewForZooming(在scrollView中:UIScrollView)-> UIView? {         返回零}

Brianster answered 2019-11-19T04:23:29Z
0 votes

如果网络视图是用于只读目的的用户,即仅用于显示网络内容使用

webView.isUserInteractionEnabled = false

这样,缩放手势将无法对其进行操作。

Sameer Bhide answered 2019-11-19T04:24:08Z
0 votes

这是Gulshan Kumar的答案的略微修改版本,在iOS 12.1.2中对我有用,并且还可以防止由于双击和旋转而导致缩放。 在我的示例中,我只是将脚本直接注入到Web视图中。 我将比例调整为60%,并且在构建源字符串时无需使用串联。

let source = "var meta = document.createElement('meta'); meta.name = 'viewport'; meta.content = 'width=device-width, initial-scale=0.6, maximum-scale=0.6, user-scalable=no'; var head = document.getElementsByTagName('head')[0]; head.appendChild(meta);"

let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)

webView.configuration.userContentController.addUserScript(script)
Scott Gardner answered 2019-11-19T04:24:35Z
0 votes

如果最好在网页加载完成后禁用“捏缩”缩放,并且还可以指定要禁用的特定URL

public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
     if let url = webView.url, url.absoluteString == "***" {                       
        webView.scrollView.pinchGestureRecognizer?.isEnabled = false
     }

    print("finish")
} 
Jin answered 2019-11-19T04:25:03Z
-1 votes

我正在处理的应用程序需要使用Javascript缩放视图。 接受的答案也阻止了JavaScript从页面内部进行缩放。我只需要禁用该应用程序用户的捏手势。 我发现的唯一解决方案是在页面加载后禁用Web视图的手势:

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    /* disable pinch gesture recognizer to allow zooming the web view by code but prevent zooming it by the user */
    for (UIGestureRecognizer *gr in self.webView.scrollView.gestureRecognizers) {
        if ([gr isKindOfClass:[UIPinchGestureRecognizer class]]) {
            gr.enabled = NO;
        }
    }
}
UrK answered 2019-11-19T04:25:30Z
-1 votes

这对我有用。 [https://gist.github.com/paulofierro/5b642dcde5ee9e86a130]

  let source: String = "var meta = document.createElement('meta');" +
  "meta.name = 'viewport';" +
  "meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';" +
  "var head = document.getElementsByTagName('head')[0];" + "head.appendChild(meta);";
  let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
  let userContentController: WKUserContentController = WKUserContentController()
  let conf = WKWebViewConfiguration()
  conf.userContentController = userContentController
  userContentController.addUserScript(script)
  let webView = WKWebView(frame: CGRect.zero, configuration: conf)
Jonny answered 2019-11-19T04:25:56Z
translate from https://stackoverflow.com:/questions/25553711/disable-magnification-gesture-in-wkwebview