Swift - WKWebView

WKWebView加载页面

import UIKit
import WebKit
class ViewController: UIViewController{
    var webView : WKWebView!
    var loadType : UISegmentedControl!
    override func viewDidLoad() {
        super.viewDidLoad()
        loadType = UISegmentedControl(items: ["显示网站","显示HTML","显示本地文件","loadData显示本地"])
        loadType.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 40)
        loadType.selectedSegmentIndex = 1
        loadType.addTarget(self, action: #selector(ViewController.typeChanged(_:)), for: .valueChanged)
        
        webView = WKWebView(frame: CGRect(x: 0, y: 40, width: self.view.bounds.size.width, height: self.view.bounds.size.height - 40))
        typeChanged(loadType)
        self.view.addSubview(webView)
        self.view.addSubview(loadType)
    }
    @objc func typeChanged(_ sender:UISegmentedControl){
        let index = sender.selectedSegmentIndex
        switch index {
        case 0:
        //设置访问的url
            let url = URL(string: "https://www.jianshu.com/u/5ab366f0368f")
        //根据url创建请求
            let urlRequest = URLRequest(url: url!)
        //加载请求
            webView.load(urlRequest)
        case 1:
            let html = "

欢迎来到:Swift学习

" webView.loadHTMLString(html, baseURL: nil) case 2: let path = Bundle.main.path(forResource: "File", ofType: "pdf") let url = URL(fileURLWithPath: path!) let urlRequest = URLRequest(url: url) webView.load(urlRequest) case 3: let path = Bundle.main.path(forResource: "File", ofType: "pdf") let url = URL(fileURLWithPath: path!) let data = try! Data(contentsOf: url) webView.load(data, mimeType: "application/pdf", characterEncodingName: "utf-8", baseURL: NSURL() as URL) default: print("出现错误") } } }

你可能感兴趣的:(Swift - WKWebView)