#import "ViewController.h" @interface ViewController ()<UISearchBarDelegate,UIWebViewDelegate> { UIWebView *_webView; UISearchBar *_searchBar; UIToolbar *toolBar;//底部工具欄 UIBarButtonItem *backButton;//回退 UIBarButtonItem *forwardButton;//前進 } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self layout]; } -(void)layout{ _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, 375, 44)]; //遵照協議 _searchBar.delegate = self; //添加瀏覽器 _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 64, 375, 559)]; _webView.delegate = self; _webView.backgroundColor = [UIColor grayColor]; [self.view addSubview:_webView]; [self.view addSubview:_searchBar]; //添加工具欄 toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 623, 375, 44)]; //設置工具欄按鈕(回退和前進) backButton = [[UIBarButtonItem alloc]initWithTitle:@"⬅️" style:UIBarButtonItemStyleDone target:self action:@selector(back)]; forwardButton = [[UIBarButtonItem alloc]initWithTitle:@"➡️" style:UIBarButtonItemStyleDone target:self action:@selector(forward)]; UIBarButtonItem *spacingButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; toolBar.items = @[backButton,spacingButton,forwardButton]; [self.view addSubview:toolBar]; } -(void)request:(NSString*)urlStr{ //建立url NSURL *url; //若是file://開頭的字符串則加載bundle中的文件 if ([urlStr hasPrefix:@"file://"]) { //1.獲取文件名位置 NSRange range = [urlStr rangeOfString:@"file://"]; NSString * fileName = [urlStr substringFromIndex:range.length]; NSLog(@"%@",fileName); //2.獲取文件位置 url = [[NSBundle mainBundle]URLForResource:fileName withExtension:nil]; }else if ([urlStr hasPrefix:@"http://"]){ url = [NSURL URLWithString:urlStr]; }else{//若是不符合任何協議則進行百度搜索 urlStr = [NSString stringWithFormat:@"https://www.baidu.com/s?wd=%@",urlStr]; //url編碼 urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; url = [NSURL URLWithString:urlStr]; } NSURLRequest *request = [NSURLRequest requestWithURL:url]; [_webView loadRequest:request]; } #pragma mark searchBar代理方法 -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ // NSLog(@"搜索:%@",searchBar.text); [self request:searchBar.text]; } #pragma mark webview代理方法 #pragma mark 開始加載 -(void)webViewDidStartLoad:(UIWebView *)webView{ [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; } #pragma mark 加載完畢 -(void)webViewDidFinishLoad:(UIWebView *)webView{ //顯示當前加載的url NSLog( @"%@",webView.request.URL); _searchBar.text = [NSString stringWithFormat:@"%@",webView.request.URL]; [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; } //回退 -(void)back{ [_webView goBack]; } //前進 -(void)forward{ [_webView goForward]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end