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

注:代码已升级至Swift4

使用网页控件(UIWebView)与工具栏控件(UIToolbar),自制一个小型的浏览器,其功能如下:

  • 输入网址,点击“Go”按钮加载网页
  • 加载过程中有进度条,同时可以点击停止按钮取消加载
  • 有页面刷新按钮
  • 有前进后退按钮
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
import UIKit

class ViewController: UIViewController, UIWebViewDelegate, UITextFieldDelegate {

@IBOutlet var btngo:UIButton!
@IBOutlet var webview:UIWebView!
@IBOutlet var txturl:UITextField!
var loadIndicator:UIActivityIndicatorView!

// 进度条计时器
var ptimer:Timer!
// 进度条控件
var progBar:UIProgressView!

override func viewDidLoad() {
super.viewDidLoad()

self.webview.delegate = self

let frame = CGRect(x: 100.0, y: 100.0, width: 32.0, height: 32.0)
loadIndicator = UIActivityIndicatorView(frame: frame)
loadIndicator.activityIndicatorViewStyle = .gray
self.view.addSubview(loadIndicator);

txturl.delegate = self

// 构建浏览器工具条
setupBrowserToolbar()
}

func setupBrowserToolbar() {
// 创建一个浏览器工具条,并设置它的大小和位置
let browserToolbar = UIToolbar(frame:CGRect(x: 0, y: 20, width: 320, height: 44))

// 将工具条添加到当前应用的界面中
self.view.addSubview(browserToolbar)

// 创建图片工具条,但是不是直接使用文件名,而是用 Data 方式初始化 UIImage
let path = Bundle.main.path(forResource: "back", ofType:"png")

let urlStr = URL(fileURLWithPath: path!);
let data = try? Data(contentsOf: urlStr);
let btnBack = UIBarButtonItem(image:UIImage(data: data!), style:.plain, target:self,
action:#selector(ViewController.backClicked(_:)));
// 第一个分隔按钮
let btnGap1 = UIBarButtonItem(barButtonSystemItem:.flexibleSpace,
target:nil, action:nil)

// 创建前进按钮 UIBarButtonItem
let btnForward = UIBarButtonItem(image:UIImage(named:"forward.png"),
style:.plain, target:self,
action:#selector(ViewController.forwardClicked(_:)))

// 第二个分隔按钮,创建一个可伸缩的UIBarButtonItem
let btnGap2 = UIBarButtonItem(barButtonSystemItem:.flexibleSpace,
target:nil, action:nil)

// 创建重新加载按钮 UIBarButtonItem
let btnReload = UIBarButtonItem(image:UIImage(named:"reload.png"),
style:.plain, target:self,
action:#selector(ViewController.reloadClicked(_:)))

// 第三个分隔按钮
let btnGap3 = UIBarButtonItem(barButtonSystemItem:.flexibleSpace,
target:nil, action:nil)

// 创建加载停止按钮
let btnStop = UIBarButtonItem(image:UIImage(named:"stop"),
style:.plain, target:self,
action:#selector(ViewController.stopClicked(_:)))

// 第四个分隔按钮
let btnGap4 = UIBarButtonItem(barButtonSystemItem:.flexibleSpace,
target:nil, action:nil)

// 创建进度工具条
progBar = UIProgressView(progressViewStyle:UIProgressViewStyle.bar)

// 设置UIProgressView的大小
progBar.frame = CGRect(x: 0 , y: 0 , width: 80, height: 20)

// 设置该进度条的初始进度为0
progBar.progress = 0

// 创建使用 UIView 的自定义的 UIBarButtonItem
let btnProg = UIBarButtonItem(customView:progBar)

// 为工具条设置工具按钮
browserToolbar.setItems([btnback,btngap1,btnforward,btngap2,btnreload,
btngap3,btnstop,btngap4, btnProg], animated:true)

// 创建计时器对象
ptimer = Timer.scheduledTimer(timeInterval: 0.2, target:self,
selector:#selector(ViewController.loadProgress),
userInfo:nil, repeats:true)
ptimer.invalidate()
}

func textFieldShouldReturn(_ textField:UITextField) -> Bool {
txturl.resignFirstResponder()
print("Url Changed!")
let url = txturl.text;
loadUrl(url!)
return true
}

/**
* 在 UIWebView 加载指定 URL
*/
func loadUrl(_ url:String) {
let urlobj = URL(string:url)
let request = URLRequest(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()
let url = txturl.text;
loadUrl(url!)
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}

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: Error) {
//999错误过滤(防止页面正在加载时候,点击stop按钮,提示NSURLErrorDomain error=-999)
if error._code == NSURLErrorCancelled {
return
}

let alertController = UIAlertController(title: "出错!",
message: error.localizedDescription,
preferredStyle: .alert)
let okAction = UIAlertAction(title: "确定", style: .cancel, handler: nil)
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :