// // ViewController.m // UIWebView // // Created by DC017 on 15/12/10. // Copyright © 2015年 DC017. All rights reserved. // #pragma mark 有搜索框 #import "ViewController.h" @interface ViewController ()<UISearchBarDelegate,UIWebViewDelegate> { //搜索欄 UISearchBar * searchbar; UIWebView * webview; UIToolbar * toolbar; UIBarButtonItem * qianjin; UIBarButtonItem * houtui; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self layout]; } -(void)layout{ searchbar =[[UISearchBar alloc]initWithFrame:CGRectMake(0, 20, 375, 44)]; [self.view addSubview:searchbar]; webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 64, 375,559)]; webview.backgroundColor=[UIColor grayColor]; [self.view addSubview:webview]; toolbar=[[UIToolbar alloc]initWithFrame:CGRectMake(0, 630, 375,44 )]; //toolbar.items=@[按鈕1,空格,按鈕2]; qianjin=[[UIBarButtonItem alloc]initWithTitle:@"前進" style:UIBarButtonItemStyleDone target:self action:@selector(qianjinI)]; houtui=[[UIBarButtonItem alloc]initWithTitle:@"後退" style:UIBarButtonItemStyleDone target:self action:@selector(houtuiI)]; //建立彈簧 UIBarButtonItem *spring = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil]; toolbar.items=@[houtui,spring,qianjin]; [self.view addSubview:toolbar]; //遵照協議 searchbar.delegate=self; webview.delegate=self; } #pragma mark searchBar 代理 -(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ [self request: searchbar.text]; } -(void)request:(NSString *)searchbartext{ NSString *strUrl=searchbartext; NSURL *url;; if ([strUrl hasPrefix:@"file://"]) { NSLog(@"sjdfj"); NSRange range=[strUrl rangeOfString:@"file://"]; NSString * fileName=[strUrl substringFromIndex:range.length]; url=[[NSBundle mainBundle]URLForResource:fileName withExtension:nil]; }else if([strUrl hasPrefix:@"http://"]){ url=[NSURL URLWithString:strUrl]; }else{ NSString * strUrlI=[NSString stringWithFormat:@"http:www.baidu.com/s?wd=%@",strUrl]; strUrl=[strUrlI stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]; url=[NSURL URLWithString:strUrlI]; } NSURLRequest * requestI=[NSURLRequest requestWithURL:url]; [webview loadRequest:requestI]; NSLog(@"%@",strUrl); //NSURLRequest } -(void)qianjinI{ [webview goForward]; } -(void)houtuiI{ [webview goBack]; } #pragma mark webview 代理協議 #pragma mark webview 加載完成 -(void)webViewDidFinishLoad:(UIWebView *)webView{ [UIApplication sharedApplication].networkActivityIndicatorVisible=NO; NSLog(@"rrrrrrr %@",webview.request.URL); searchbar.text=[NSString stringWithFormat:@"%@",webview.request.URL]; } #pragma mark webview 開始加載 -(void)webViewDidStartLoad:(UIWebView *)webView{ [UIApplication sharedApplication].networkActivityIndicatorVisible=YES; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end