iOS-swift WebView瀏覽器
阿新 • • 發佈:2019-02-01
UIWebVIew(不支援ios10及其以上的版本)
import UIKit
class FourViewController: UIViewController,UIWebViewDelegate {
//內部瀏覽器(webview)
@IBOutlet var webview1: UIWebView!
//網址輸入框
@IBOutlet var textFile1: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
//設定webview控制元件的 Delegate 的監聽
webview1.delegate=self
//開啟一個外部的網頁
webview1.loadRequest(NSURLRequest(url: NSURL(string: "http://hao123.com")! as URL) as URLRequest)
// Do any additional setup after loading the view.
}
//返回
@IBAction func backButClick(_ sender: UIButton) {
webview1.goBack()
}
//前進
@IBAction func toButClick(_ sender: UIButton) {
webview1.goForward()
}
//重新整理
@IBAction func reloadButClick(_ sender: UIButton) {
webview1.reload()
}
//載入
@IBAction func goButClick(_ sender: UIButton) {
let text_url = textFile1.text
webview1.loadRequest(NSURLRequest(url: NSURL(string : text_url!)! as URL) as URLRequest)
}
//網頁開始載入監聽
func webViewDidStartLoad(_ webView: UIWebView) {
print("開始載入")
}
//網頁結束載入監聽
func webViewDidFinishLoad(_ webView: UIWebView) {
print("結束載入")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
WKWebView(支援ios8以上的系統,比UIWebView效能更加的優化,用法跟UIWebView用法差不多)
import UIKit
import WebKit //引入該包
class WebViewController: UIViewController {
//輸入網址的文字輸入框
@IBOutlet var textfile1: UITextField!
//瀏覽器控制元件
@IBOutlet var webview2: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
//重新整理
@IBAction func refreshClick(_ sender: AnyObject) {
webview2.reload()
}
//前進
@IBAction func toClick(_ sender: AnyObject) {
webview2.goForward()
}
//後退
@IBAction func backClick(_ sender: AnyObject) {
webview2.goBack()
}
//搜尋
@IBAction func searchClick(_ sender: AnyObject) {
let urls = textfile1.text
// print(urls)
webview2.load(NSURLRequest(url: NSURL(string: urls!)! as URL)as URLRequest)
}
//文字輸入框輸入完成後觸發的事件
@IBAction func textEndOnExit(_ sender: AnyObject) {
//隱藏鍵盤(讓文字框失去焦點)
textfile1.resignFirstResponder()
}
//點選空白處讓鍵盤消失(這個事件要將 View改為UIControl)
@IBAction func touchUpInside(_ sender: UIControl) {
//隱藏鍵盤(讓文字框失去焦點)
textfile1.resignFirstResponder()
}
//觸控事件,當一個或多個手指離開螢幕時觸發(當手指離開輸入框後鍵盤消失)
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
//隱藏鍵盤(讓文字框失去焦點)
textfile1.resignFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
將 View改為UIControl
點選View在右邊將 class改為UIControl