实战 - 简易浏览器搜索

学习本章,先掌握WKWebView,UIToolbar,UITextField

import UIKit
import WebKit
class ViewController: UIViewController,UITextFieldDelegate,WKUIDelegate,WKNavigationDelegate{
    var GoBt:UIButton!
    var WebView:WKWebView!
    var addressUrl:UITextField!
    var loadIndicator:UIActivityIndicatorView!
    var ProTimer:Timer!
    var ProBar:UIProgressView!
    override func viewDidLoad() {
        super.viewDidLoad()
        //初始化addressUrl,并添加到视图中
        addressUrl = UITextField(frame: CGRect(x: 0, y: 70, width: self.view.bounds.size.width - 40, height: 50))
        addressUrl.borderStyle = .roundedRect
        addressUrl.delegate = self
        self.view.addSubview(addressUrl)
        //初始化GoBt并添加到视图中
        GoBt = UIButton(frame: CGRect(x: self.view.bounds.size.width - 40, y: 70, width: 40, height: 40))
        GoBt.setImage(UIImage(named:"search"), for: .normal)
        GoBt.addTarget(self, action: #selector(ViewController.goClicked), for: .touchUpInside)
        self.view.addSubview(GoBt)
        //初始化WkWebView,并添加到视图中
        WebView = WKWebView(frame: CGRect(x: 0, y: 120, width: self.view.bounds.size.width, height: self.view.bounds.size.height-120))
        self.view.addSubview(WebView)
        self.WebView.uiDelegate = self
        self.WebView.navigationDelegate = self
        //初始化loadIndicator
        loadIndicator = UIActivityIndicatorView(frame: CGRect(x: 150, y: 250, width: 40, height: 40))
        loadIndicator.color = UIColor.black
        self.view.addSubview(loadIndicator)
        //设置浏览器toolbal
        setUpBrowserToolbal()
    }
    func setUpBrowserToolbal(){
        //初始化浏览器toolbal
        let browserToolbal = UIToolbar(frame: CGRect(x: 0, y: 20, width: self.view.bounds.size.width, height: 44))
        //返回按钮
        let BackBt = UIBarButtonItem(image: UIImage(named:"back"), style: .plain, target: self, action: #selector(ViewController.backClicked))
        //前进按钮
        let ForWardBt = UIBarButtonItem(image: UIImage(named:"forward"), style: .plain, target: self, action: #selector(ViewController.forwardClicked))
        //重新加载按钮
        let ReLoadBt = UIBarButtonItem(image: UIImage(named:"load"), style: .plain, target: self, action: #selector(ViewController.reloadClicked))
        //停止加载按钮
        let StopBt = UIBarButtonItem(image:UIImage(named: "stop"), style: .plain, target: self, action: #selector(ViewController.stopClicked))
        //进度条按钮
        ProBar = UIProgressView(progressViewStyle: .bar)
        ProBar.frame = CGRect(x: 0, y: 0, width: 80, height: 20)
        ProBar.progress = 0
        let ProBt = UIBarButtonItem(customView: ProBar)
        //间隔
        let gap1 = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        let gap2 = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        let gap3 = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        let gap4 = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil)
        browserToolbal.setItems([BackBt,gap1,ForWardBt,gap2,ReLoadBt,gap3,StopBt,gap4,ProBt], animated: true)
        self.view.addSubview(browserToolbal)
        //创建计时器对象
        ProTimer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(ViewController.loadProgress), userInfo: nil, repeats: true)
        ProTimer.invalidate()
    }
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        addressUrl.resignFirstResponder()
        print("url changed!")
        let url = addressUrl.text
        loadUrl(url!)
        return true
    }
    
    func loadUrl(_ url:String){
        let urlobj = URL(string: url)
        let request = URLRequest(url: urlobj!)
        WebView.load(request)
    }
    
    @objc func goClicked(){
        addressUrl.resignFirstResponder()
        let url = addressUrl.text
        loadUrl(url!)
    }
    
    @objc func backClicked(){
        WebView.goBack()
    }
    
    @objc func forwardClicked(){
        WebView.goForward()
    }
    
    @objc func reloadClicked(){
        WebView.reload()
    }
    
    @objc func stopClicked(){
        WebView.stopLoading()
    }
    
    @objc func loadProgress(){
        //进度满了,停止计时器
        if ProBar.progress >= 1.0{
            ProTimer.invalidate()
        }else{
            //改变进度条的进度值
            ProBar.setProgress(ProBar.progress + 0.02, animated: true)
        }
    }
    
    func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
        ProBar.setProgress(0, animated:false)
        ProTimer.fire()
        loadIndicator.startAnimating()
    }
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        loadIndicator.stopAnimating()
        ProBar.setProgress(1, animated: true)
        ProTimer.invalidate()
    }
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        //999错误过滤(放置页面正在加载时候,点击stop按钮,提示NSURLErrorDomain error=-999)
        if error._code == NSURLErrorCancelled{
            return
        }
        let alertController = UIAlertController(title: "出错", message: error.localizedDescription, preferredStyle: .alert)
        let OK = UIAlertAction(title: "确定", style: .default, handler: nil)
        alertController.addAction(OK)
        self.present(alertController, animated: true, completion: nil)
    }
    
}

你可能感兴趣的:(实战 - 简易浏览器搜索)