IOS学习之UIWebView(3)

1、语言:swift2

2、浏览器简单示例

     控件如下:

IOS学习之UIWebView(3)_第1张图片

3、ViewController继承

      viewController需要继承UIWebViewDelegate, UITextFieldDelegate


4、实现了协议

        实现了UIWebViewDelegateUITextFieldDelegate中的部分协议。

5、源码如下:

import UIKit

class ViewController: UIViewController,UIWebViewDelegate, UITextFieldDelegate{

    @IBOutlet weak var webView: UIWebView!
    @IBOutlet weak var searchBtn: UIButton!
    @IBOutlet weak var urlText: UITextField!
    
    /// 指示器
    var loadIndicator : UIActivityIndicatorView!;
    
    override func viewDidLoad()
    {
        super.viewDidLoad();
        
        
        /// 设置委托
        webView.delegate = self;
        
        /// 指示器对象
        loadIndicator = UIActivityIndicatorView(frame: CGRectMake(100.0, 100.0, 32.0, 32.0));
       
        loadIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray;
        
        view.addSubview(loadIndicator);
        
        urlText.delegate = self;
    }

    /// 文本框的协议:当点击输入框键盘上的go 按钮后,调用该协议
    func textFieldShouldReturn(textField:UITextField)->Bool
    {
        /// 触发键盘隐藏事件
        urlText.resignFirstResponder();
        let url = urlText.text;
    
        loadUrl(url!);
        
        return true;
    }
    
    /// 前往网址
    func loadUrl(url:String)
    {
        let urlObj = NSURL(string: url);
        
        let request = NSURLRequest(URL:urlObj!);
        
        webView.loadRequest(request);
    }
    
    
    /// 搜索按钮被点击事件
    @IBAction func searchBtnclicked(sender: AnyObject)
    {
        /// 收起键盘
        urlText.resignFirstResponder();
        let url = urlText.text;
        loadUrl(url!);
    }
    
    /// UIWebView协议实现
    func webViewDidStartLoad(webView: UIWebView) {
        /// 设置加载动画
        loadIndicator.startAnimating();
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        loadIndicator.stopAnimating();
    }
    
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?)
    {
        /// 提示框
        let alert = UIAlertController(title: "提示", message: error?.localizedDescription, preferredStyle: UIAlertControllerStyle.Alert);
        let action = UIAlertAction(title:"确定", style: UIAlertActionStyle.Default, handler: nil);
        alert
            .addAction(action);
        presentViewController(alert, animated: true, completion: nil);
        
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }


}

你可能感兴趣的:(Web,UI,View控件示例,浏览器简单示例)