Swift - 使用UIWebView和UIToolbar制作一个浏览器

使用网页控件(UIWebView)与工具栏控件(UIToolbar),我们可以自制一个小型的浏览器,其功能如下:
1,输入网址,点击“Go”按钮加载网页
2,加载过程中有进度条,同时可以点击停止按钮取消加载
3,有页面刷新按钮
4,有前进后退按钮
 
效果图如下:


代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
class ViewController: UIViewController, UIWebViewDelegate,UITextFieldDelegate {
     
    @IBOutlet var btngo:UIButton!
    @IBOutlet var webview:UIWebView!
    @IBOutlet var txturl:UITextField!
    var loadIndicator:UIActivityIndicatorView!
     
    //进度条计时器
    var ptimer:NSTimer!
    //进度条控件
    var progBar:UIProgressView!
     
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
         
        self.webview.delegate = self;
        loadIndicator = UIActivityIndicatorView(frame: CGRectMake(100.0, 100.0, 32.0, 32.0));
        loadIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
        self.view.addSubview(loadIndicator);
         
        txturl.delegate = self
         
         
        //构建浏览器工具条
        setupBrowserToolbar()
    }
     
    func setupBrowserToolbar()
    {
        // 创建一个浏览器工具条,并设置它的大小和位置
        var browserToolbar =  UIToolbar(frame:CGRectMake(0, 20, 320, 44))
         
        // 将工具条添加到当前应用的界面中
        self.view.addSubview(browserToolbar)
         
        //创建图片工具条,但是不是直接使用文件名,而是用 NSData 方式初始化 UIImage
        var path = NSBundle.mainBundle().pathForResource("back", ofType:"png")
         
        var urlStr = NSURL.fileURLWithPath(path!);
        var data = NSData(contentsOfURL:urlStr!);
        var btnback =  UIBarButtonItem(image:UIImage(data: data!),
          style:UIBarButtonItemStyle.Bordered, target:self,action:Selector("backClicked:"));
        //第一个分隔按钮
        var btngap1 =  UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace,
            target:nil,
            action:nil);
        // 创建前进按钮 UIBarButtonItem
        var btnforward = UIBarButtonItem(image:UIImage(named:"forward.png"),
          style:UIBarButtonItemStyle.Plain, target:self, action:Selector("forwardClicked:"));
         
        // 第二个分隔按钮,创建一个可伸缩的UIBarButtonItem
        var btngap2 =  UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace,
            target:nil,
            action:nil);
         
        // 创建重新加载按钮 UIBarButtonItem
        var btnreload = UIBarButtonItem(image:UIImage(named:"reload.png"),
          style:UIBarButtonItemStyle.Plain, target:self, action:Selector("reloadClicked:"));
         
        //第三个分隔按钮
        var btngap3 =  UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace,
            target:nil,
            action:nil);
         
        //创建加载停止按钮
        var btnstop = UIBarButtonItem(image:UIImage(named:"stop"),
          style:UIBarButtonItemStyle.Plain, target:self, action:Selector("stopClicked:"));
         
        //第四个分隔按钮
        var btngap4 =  UIBarButtonItem(barButtonSystemItem:UIBarButtonSystemItem.FlexibleSpace,
            target:nil,
            action:nil);
         
        //创建进度工具条
        progBar = UIProgressView(progressViewStyle:UIProgressViewStyle.Bar)
         
        // 设置UIProgressView的大小
        progBar.frame = CGRectMake(0 , 0 , 80, 20)
         
        // 设置该进度条的初始进度为0
        progBar.progress = 0
         
        // 创建使用 UIView 的自定义的 UIBarButtonItem
        var btnprog =  UIBarButtonItem(customView:progBar)
         
        // 为工具条设置工具按钮
        browserToolbar.setItems( [btnback,btngap1, btnforward,btngap2,
          btnreload,btngap3, btnstop,btngap4, btnprog ], animated:true)
         
        //创建计时器对象
        ptimer = NSTimer.scheduledTimerWithTimeInterval(0.2,
            target:self ,selector: Selector("loadProgress"),
            userInfo:nil,repeats:true);
        ptimer.invalidate()
    }
     
    func textFieldShouldReturn(textField:UITextField) -> Bool
    {
        txturl.resignFirstResponder()
        println("url Changed!")
        var url = txturl.text;
        loadUrl(url)
        return true
    }
    /*
        在 UIWebView 加载指定 URL
    */
    func loadUrl(url:String)
    {
        var urlobj = NSURL(string:url)
         
        var request = NSURLRequest(URL:urlobj!)
         
        webview.loadRequest(request);
    }
     
    func stopClicked(sender:UIBarButtonItem)
    {
        webview.stopLoading()
    }
     
    func reloadClicked(sender:UIBarButtonItem)
    {
        webview.reload()
    }
     
    func backClicked(sender:UIBarButtonItem)
    {
        webview.goBack()
    }
     
    func forwardClicked(sender:UIBarButtonItem)
    {
        webview.goForward()
    }
     
    @IBAction func goClicked(sender:UIButton)
    {
        //收起输入面板
        txturl.resignFirstResponder()
        var url = txturl.text;
        loadUrl(url)
    }
     
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
     
     
    func webViewDidStartLoad(webView:UIWebView)
    {
        progBar.setProgress(0, animated:false);
        ptimer.fire();
        loadIndicator.startAnimating();
    }
    func webViewDidFinishLoad(webView:UIWebView)
    {
        loadIndicator.stopAnimating();
        progBar.setProgress(1, animated:true);
        ptimer.invalidate();
    }
    func loadProgress()
    {
        // 如果进度满了,停止计时器
        if(progBar.progress >= 1.0)
        {
            // 停用计时器
            ptimer.invalidate();
        }
        else
        {
            // 改变进度条的进度值
            progBar.setProgress(progBar.progress + 0.02, animated:true);
        }
    }
     
    func webView(webView: UIWebView!, didFailLoadWithError error: NSError!)
    {
        var alertview = UIAlertView();
        alertview.title = "出错!"
        alertview.message = error.localizedDescription;
        alertview.addButtonWithTitle("确定")
        alertview.show();
    }  
}

源代码下载:使用UIWebView制作一个浏览器.zip
posted @ 2015-09-25 14:47  brave-sailor  阅读(291)  评论(0编辑  收藏  举报