首页 > 解决方案 > wkWebview 跨界 swift IOS

问题描述

我正在尝试使用带有 wkwebview 的 webview 制作应用程序,但我的 webview 在 iphone 中越过了缺口,如何让我的 webview 不越过缺口

这是我的视图控制器

在此处输入图像描述

这是我的代码

var webView: WKWebView!
var popupWebView: WKWebView?
var urlPath: String = "https://twitter.com"

override func viewDidLoad() {
    super.viewDidLoad()
    setupWebView()
    loadWebView()
}
func setupWebView() {
    let preferences = WKPreferences()
    preferences.javaScriptCanOpenWindowsAutomatically = true
    let prefs = WKWebpagePreferences()
    prefs.allowsContentJavaScript = true
    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences
    configuration.defaultWebpagePreferences = prefs
    webView = WKWebView(frame: view.bounds, configuration: configuration)
    webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
    webView.uiDelegate = self
    webView.allowsBackForwardNavigationGestures = true
    webView.navigationDelegate = self
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(refreshWebView(_:)), for: UIControl.Event.valueChanged)
    webView.scrollView.addSubview(refreshControl)
    webView.scrollView.bounces = true
    webView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(webView)
    NSLayoutConstraint.activate([
        webView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
        webView.topAnchor.constraint(equalTo: self.view.safeAreaLayoutGuide.topAnchor),
        webView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor),
        webView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor)
    ])

}

func loadWebView() {
    logger.log("loadwebview")
    if let url = URL(string: urlPath) {
        let urlRequest = URLRequest(url: url)
        self.view = webView
        webView.load(urlRequest)
    }
}

这是我的结果

在此处输入图像描述

如何使我的网络视图处于缺口之下

更新结果 在此处输入图像描述

谢谢

标签: iosswiftxcode

解决方案


将布局约束添加到 WebView 并使它们与 safearealayoutguide 相关,以确保您的 webview 不会跨越您指定的顶部和底部“缺口”。

用这些行setupWebView替换 view.addSubview(webView)

            webView.translatesAutoresizingMaskIntoConstraints = false
            view.addSubview(webView)
            NSLayoutConstraint.activate([webView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
                                         webView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
                                         webView.trailingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.trailingAnchor),
                                         webView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)])

如果您希望您的 webView 溢出到底部安全区域(内容低于底部凹槽),只需safeAreaLayoutGuidewebView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)to删除webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)


推荐阅读