製做一個簡單的瀏覽器,包含網址輸入框,Search按鈕,前進、回退按鈕,UIWebView就這幾個簡單的控件。web
UITextField:用來輸入網址;瀏覽器
UIbuttom:實現前進,後退,搜索等功能;ide
UIWebView:實現網頁展現。網站
準備工做:url
右鍵Info.plist並Open As Source Code,打開以後添加如下代碼段:spa
1 <key>NSAppTransportSecurity</key> 2 <dict> 3 <key>NSAllowsArbitraryLoads</key> 4 <true/> 5 </dict>
以上代碼段功能:有些網址爲Http,要搞成Https,具體原理之後探索出來了再補充。3d
言歸正傳,實現瀏覽器功能的具體代碼以下:code
1 #import "ViewController.h" 2 3 @interface ViewController (){ 4 5 // 定義全局變量,各個控件 6 UIWebView *mywebview; 7 UIButton *backbutton; 8 UIButton *goforbutton; 9 UITextField *urlField; 10 UIButton *searchButton; 11 } 12 13 @end 14 15 @implementation ViewController 16 17 - (void)viewDidLoad { 18 [super viewDidLoad]; 19 20 // 添加瀏覽器view, 21 mywebview = [[UIWebView alloc]initWithFrame:CGRectMake(0, 70, self.view.frame.size.width, self.view.frame.size.height-120)]; 22 [self.view addSubview:mywebview]; 23 24 25 // 網址輸入框 26 urlField = [[UITextField alloc]initWithFrame:CGRectMake(0, 20, self.view.frame.size.width-100, 50)]; 27 urlField.borderStyle = UITextBorderStyleRoundedRect; 28 urlField.text= mywebview.request.URL.absoluteString; 29 [self.view addSubview:urlField]; 30 31 32 33 // search button 34 searchButton = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-100, 20, 100, 50)]; 35 searchButton.backgroundColor = [UIColor redColor]; 36 [searchButton setTitle:@"Search" forState:UIControlStateNormal]; 37 [searchButton addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside]; 38 [self.view addSubview:searchButton]; 39 40 41 // 返回按鍵 42 backbutton = [[UIButton alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height-50, 100, 50)]; 43 backbutton.backgroundColor = [UIColor redColor]; 44 [backbutton setTitle:@"返回" forState:UIControlStateNormal]; 45 [backbutton addTarget:self action:@selector(backFbution:) forControlEvents:UIControlEventTouchUpInside]; 46 [self.view addSubview:backbutton]; 47 48 // 前進按鈕 49 goforbutton = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-100, self.view.frame.size.height-50, 100, 50)]; 50 goforbutton.backgroundColor = [UIColor redColor]; 51 [goforbutton setTitle:@"前進" forState:UIControlStateNormal]; 52 [goforbutton addTarget:self action:@selector(goFobution:) forControlEvents:UIControlEventTouchUpInside]; 53 [self.view addSubview:goforbutton]; 54 55 56 } 57 58 59 //返回按鈕綁定事件 60 -(void)backFbution:(id)sender{ 61 [mywebview goBack]; 62 } 63 64 65 //前進按鈕綁定事件 66 -(void)goFobution:(id)sender{ 67 [mywebview goForward]; 68 } 69 70 71 //搜索按鈕綁定事件 72 -(void)search:(id)sender{ 73 [mywebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlField.text]]]; 74 } 75 76 77 - (void)didReceiveMemoryWarning { 78 [super didReceiveMemoryWarning]; 79 } 80 81 @end
運行效果以下(請無視UI所用顏色。。。。。):orm
存在一個問題,就是我在百度裏面隨便點擊一個網址連接以後,能夠打開網址,但打開以後瀏覽器的網址輸入框中的網址依然是以前那個,沒有改變爲當前網站地址。這個問題遺留下來。。。blog