如何将多个HTML文件添加到WebKit View?

时间:2018-09-06 13:19:19

标签: ios swift

简介

我正在设计一个历史应用程序。我想向其中添加多个HTML文件 WebKit视图。我不知道该怎么做。

示例

当我单击"Button 1"时,Webkit将加载"file1.html"。我没有写任何关于代码的东西,我很困惑。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

嗯,有很多方法可以做到,但是我将举一个最简单的例子。只需创建一种加载 .html 文件的方法,然后在操作按钮下调用或调用它即可。

例如:

import UIKit
import WebKit


class ExampleController: UIViewController {

@IBOutlet weak var myButton: UIButton!
@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    webView.navigationDelegate = self

}

@IBAction func firstButtonPressed(_ sender: UIButton) {
    // Here you can call your method to load html page.
    loadPage(pageName: "privacy_policy")        
}

@IBAction func secondButtonPressed(_ sender: UIButton) {
     // Here you can call different html page.
    loadPage(pageName: "terms")
}

// With this method you can call html page by it name (as parameter)
fileprivate func loadPage(pageName: String) {
    let url = Bundle.main.url(forResource: pageName, withExtension: "html")
    // file url is ready lets to add it as parameter for webView.
    webView.loadFileURL(url!, allowingReadAccessTo: url!)
}
}

extension AboutAppController: WKNavigationDelegate {

   func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
       // Here you can add start your animations (like activity indicator)
   }

   func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
       // And here finish your animations.
   }
}