创建界面
var webView : UIWebView!
var toolBar : UIToolbar!
let swiftWH = UIScreen.mainScreen().bounds.size
webView = UIWebView(frame: CGRectMake(0, 20, swiftWH.width, swiftWH.height-49-20))
webView.delegate = self
webView.scrollView.bounces = false//禁止弹跳
self.view.addSubview(webView)
webView.loadRequest(NSURLRequest(URL: NSURL(string: "https://www.baidu.com")!))
self.createToolBarView()//工具栏
创建工具栏
func createToolBarView(){
let swiftWH = UIScreen.mainScreen().bounds.size
toolBar = UIToolbar(frame: CGRectMake(0, swiftWH.height-49, swiftWH.width, 49))
self.view.addSubview(toolBar)
let backBtn = UIBarButtonItem(title: "后退", style: .Plain, target: self, action: Selector("backClick:"))
let forwardBtn = UIBarButtonItem(title: "前进", style: .Plain, target: self, action: Selector("forwardClick:"))
let refrashBtn = UIBarButtonItem(title: "刷新", style: .Plain, target: self, action: Selector("refrashClick:"))
let stopBtn = UIBarButtonItem(title: "停止", style: .Plain, target: self, action: Selector("stopClick:"))
let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
toolBar.setItems([backBtn,space,forwardBtn,space,refrashBtn,space,stopBtn], animated: true)
}
前进 后退 刷新 停止
func backClick(sender : UIBarButtonItem){
webView.goBack()
}
func forwardClick(sender : UIBarButtonItem){
webView.goForward()
}
func refrashClick(sender : UIBarButtonItem){
webView.reload()
}
func stopClick(sender : UIBarButtonItem){
webView.stopLoading()
}
UIWebViewDelegate
func webViewDidStartLoad(webView: UIWebView) {
//开始加载网页
print("开始加载数据")
}
func webViewDidFinishLoad(webView: UIWebView) {
//网页加载结束
print("网页加载结束")
if let titleStr = webView.stringByEvaluatingJavaScriptFromString("document.title"){
print(titleStr)
}
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
//网页加载失败
print("网页加载失败")
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//点击网页上的链接
let loadUrlStr = request.URL!
print(loadUrlStr)
if navigationType == UIWebViewNavigationType.LinkClicked{//点击链接
return false
}
return true
}
来源:http://www.cnblogs.com/spaceID/p/4990665.html