禁用 WKWebView 的水平滚动

Disable horizontal scrolling for WKWebView

我知道如何为 UIWebView 执行此操作,但它已被弃用。我已经想出如何隐藏垂直和水平滚动指示器、禁用滚动视图弹跳和禁用捏合手势识别器,但仍然没有找到完全禁用 Web 视图中水平滚动的方法。任何帮助将不胜感激,下面是我的 WebView.Swift.

struct WebView: UIViewRepresentable
{
    let request: URLRequest
    var webView: WKWebView?
    
    init (request: URLRequest)
    {
        self.webView = WKWebView()
        self.request = request
        webView?.scrollView.showsHorizontalScrollIndicator = false
        webView?.scrollView.showsVerticalScrollIndicator = false
        
        webView?.scrollView.pinchGestureRecognizer?.isEnabled = false
        webView?.scrollView.bounces = false
    }
    
    func makeUIView(context: Context) -> WKWebView {
        return webView!
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)
    }
    
    func goBack()
    {
        webView?.goBack()
    }
    
    func refresh()
    {
        webView?.reload()
    }
    
    func goHome()
    {
        webView?.load(request)
    }
}

为此,您可以使用 CoordinatorThere is good explanation for their.
在您的 UIViewRepresentable 中创建 class Coordinator。将 UIScrollViewDelegate 添加到 class。在makeUIView中设置webView?.scrollView.delegate = context.coordinator.
在Coordinator中,你需要这个功能。

func scrollViewDidScroll(_ scrollView: UIScrollView) {
    if (scrollView.contentOffset.x > 0){
        scrollView.contentOffset = CGPoint(x: 0, y: scrollView.contentOffset.y)
    }
 }

And now, horizontal scroll not work!
所有代码

import WebKit

struct WebView: UIViewRepresentable {
    let request: URLRequest
    var webView: WKWebView?
    
    class Coordinator: NSObject, UIScrollViewDelegate {
        var parent: WebView
        
        init(_ parent: WebView) {
            self.parent = parent
        }
        
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            if (scrollView.contentOffset.x > 0){
                scrollView.contentOffset = CGPoint(x: 0, y: scrollView.contentOffset.y)
            }
         }
    }
    
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    
    init (request: URLRequest) {
        self.webView = WKWebView()
        self.request = request
        webView?.scrollView.showsHorizontalScrollIndicator = false
        webView?.scrollView.showsVerticalScrollIndicator = false
        
        webView?.scrollView.pinchGestureRecognizer?.isEnabled = false
        webView?.scrollView.bounces = false
    }
    
    func makeUIView(context: Context) -> WKWebView {
        webView?.scrollView.delegate = context.coordinator
        return webView!
    }
    
    func updateUIView(_ uiView: WKWebView, context: Context) {
        uiView.load(request)
    }
    
   // You funcs
}