以编程方式添加WKWebView

时间:2018-12-17 03:41:42

标签: ios wkwebview activity-indicator

我是iOS开发的初学者,一直很难添加带有代码的WKWebview。我也打算将其设置为全宽,但屏幕空白。

var webView = WKWebView()
var activityIndicatorView: ActivityIndicatorView!

override func viewDidLoad() {
    super.viewDidLoad() 
     //show Activity Indicator
    self.activityIndicatorView = ActivityIndicatorView(title: "Loading content...", center: self.view.center)
    self.activityIndicatorView.startAnimating();
    self.view.addSubview(self.activityIndicatorView.getViewActivityIndicator())self.view.addSubview(self.activityIndicatorView.getViewActivityIndicator())
    // Do any additional setup after loading the view.
    let urlString = "http://www.youtube.com";
    let request = URLRequest(url:URL(string: urlString)!)
    self.webView.load(request)
     self.view = webView
}

3 个答案:

答案 0 :(得分:0)

您正在创建一个零帧的webView,这就是为什么它不显示的原因。

webView = WKWebView(frame: .zero)更改为此:

webView = WKWebView(frame: self.view.frame)

要在加载页面时显示活动指示器,您需要实现WKNavigationDelegate委托。将您的代码更新为此:

class ViewController: UIViewController, WKNavigationDelegate {
    var webView = WKWebView()
    var activityIndicatorView: ActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad() 
         //show Activity Indicator
        self.activityIndicatorView = ActivityIndicatorView(title: "Loading content...", center: self.view.center)
        self.activityIndicatorView.startAnimating();
        self.view.addSubview(self.activityIndicatorView.getViewActivityIndicator())self.view.addSubview(self.activityIndicatorView.getViewActivityIndicator())
        // Do any additional setup after loading the view.
        let urlString = "http://www.youtube.com";
        let request = URLRequest(url:URL(string: urlString)!)
        self.webView.navigationDelegate = self // Add this line!
        self.webView.load(request)
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        self.view = webView
        // Hide activity indicator here
    }
}

答案 1 :(得分:0)

let webview = WKWebView()
    webview.frame  = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 100)
    webview.load(URLRequest(url: Bundle.main.url(forResource: "index", withExtension:"html", subdirectory: "subdirectories")! as URL) as URLRequest)
    self.view.addSubview(webview)

答案 2 :(得分:0)

像这样使用:

lazy var webView: WKWebView = {
    let wv = WKWebView()
    wv.uiDelegate = self
    wv.navigationDelegate = self
    wv.translatesAutoresizingMaskIntoConstraints = false
    return wv
}()


override func viewDidLoad() {
    super.viewDidLoad()

    view.addSubview(webView)
    NSLayoutConstraint.activate([
        webView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        webView.topAnchor.constraint(equalTo: view.topAnchor),
        webView.rightAnchor.constraint(equalTo: view.rightAnchor),
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor)])
}