在iOS 10中使用WKWebView

问题描述 投票:0回答:1

我试图在iOS 10中使用WKWebView并遇到与NSCoding相关的错误。

在搜索它时,我遇到了this article,因此决定以编程方式实现它。

我在故事板中添加了一个视图控制器,然后我将WKUIDelegate添加到我的控制器中。但即使在那之后,我也没有看到网页显示在我的屏幕上。

我的视图控制器充当Web视图代码:

import UIKit
import WebKit

class WebViewController: UIViewController, WKUIDelegate {
    var webView: WKWebView!
    var articleURL: URL?
    @IBOutlet var webViewContainer: UIView!

    override func loadView() {
        super.loadView()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        let webConfiguration = WKWebViewConfiguration()
        let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.webViewContainer.frame.size.height))
        self.webView = WKWebView (frame: customFrame , configuration: webConfiguration)
        webView.translatesAutoresizingMaskIntoConstraints = false
        self.webViewContainer.addSubview(webView)
        webView.topAnchor.constraint(equalTo: webViewContainer.topAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: webViewContainer.rightAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: webViewContainer.leftAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor).isActive = true
        webView.heightAnchor.constraint(equalTo: webViewContainer.heightAnchor).isActive = true
        webView.uiDelegate = self

        guard let url = articleURL else {
            return
        }
        let myRequest = URLRequest(url: url)
        webView.load(myRequest)
    }
}

我从我以前的控制器进入这个控制器。 segue代码:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "webPage" {
        let controller = (segue.destination as? WebViewController)!
        controller.articleURL = movieReview?.articleURL
    }
}

故事板图片:

enter image description here

我实际上正在导航到视图,但它是空白的。当我调试时,我的代码执行'webView.load(myRequest)',但我没有在屏幕上看到任何内容。

我还缺少什么?

ios swift wkwebview
1个回答
0
投票

首先检查您的webViewContainer视图是否已连接到storyboard viewcontroller中。如果它已经连接并且约束设置正确就可以了。然后像这样对webview进行约束。从self.view添加约束而不是self.webview,添加到容器webview后是父视图的子项,所以最好将self.view中的约束添加到webView。希望这样可行。

self.view.addConstraint(NSLayoutConstraint(item: webView, attribute: .trailing, relatedBy: .equal, toItem: self.webViewContainer, attribute: .trailing, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: webView, attribute: .leading, relatedBy: .equal, toItem: self.webViewContainer, attribute: .leading, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: webView, attribute: .top, relatedBy: .equal, toItem: self.webViewContainer, attribute: .top, multiplier: 1, constant: 0))
self.view.addConstraint(NSLayoutConstraint(item: webView, attribute: .bottom, relatedBy: .equal, toItem: self.webViewContainer, attribute: .bottom, multiplier: 1, constant: 0))
© www.soinside.com 2019 - 2024. All rights reserved.