// // ViewController.m // 模擬UIWebView // // Created by dc0061 on 15/12/10. // Copyright © 2015年 dc0061. All rights reserved. // #import "ViewController.h" @interface ViewController ()<UISearchBarDelegate,UIWebViewDelegate> { UISearchBar *_bar; UIWebView *_webView; UIToolbar *_toolbar; UIBarButtonItem *_backButton; UIBarButtonItem *_forwarButton; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self layout]; } - (void) layout{ //添加搜索欄 _bar=[[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, 375, 50)]; _bar.delegate=self; [self.view addSubview:_bar]; //添加瀏覽器 _webView =[[UIWebView alloc]initWithFrame:CGRectMake(0, 90, 375, 527)]; _webView.delegate=self; [self.view addSubview:_webView]; _toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 617, 375, 50)]; [self.view addSubview:_toolbar]; _backButton =[[UIBarButtonItem alloc]initWithTitle:@"返回⬅️" style:UIBarButtonItemStyleDone target:self action:@selector(fanhui)]; _forwarButton =[[UIBarButtonItem alloc]initWithTitle:@"前進→" style:UIBarButtonItemStyleDone target:self action:@selector(qianjin)]; //空按鈕,沒有點擊事件 UIBarButtonItem *btnSpacing=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil]; _toolbar.items=@[_backButton,btnSpacing,_forwarButton]; } #pragma mark UISearchBar代理方法 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar{ [self request:searchBar.text]; } #pragma mark UIWebView開始時調用的方法 -(void) webViewDidStartLoad:(UIWebView *)webView{ NSLog(@"UIWebView開始時調用的方法"); [UIApplication sharedApplication].networkActivityIndicatorVisible=YES; } #pragma mark UIWebView加載結束時調用的方法 - (void) webViewDidFinishLoad:(UIWebView *)webView{ _bar.text=[NSString stringWithFormat:@"%@",webView.request.URL]; [UIApplication sharedApplication].networkActivityIndicatorVisible=NO; } - (void) request : (NSString *) name{ NSURL *url; if([name hasPrefix:@"file://"]){ //1獲取文件位置 NSRange rang=[name rangeOfString:@"file://"]; NSString *urlName=[name substringFromIndex:rang.length]; //獲取文件位置 url=[[NSBundle mainBundle]URLForResource:urlName withExtension:nil]; }else{ NSString *str=[NSString stringWithFormat:@"http://www.baidu.com/s?&wd=%@",name]; str=[str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];//將url先進行編碼 url=[NSURL URLWithString:str]; } [_webView loadRequest:[NSURLRequest requestWithURL:url]]; } - (void) fanhui{ [_webView goBack]; } - (void) qianjin{ [_webView goForward]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } @end