UIWebView是內置瀏覽器控件,能夠用來瀏覽網頁,文檔等,今天就試着作一個簡易的瀏覽器!web
定義url的初始化方法和返回,前進,刷新三個方法,實現UIWebViewDelegate協議瀏覽器
@interface WebViewController : BaseViewController<UIWebViewDelegate>{ NSString *_url; } -(id)initWithUrl:(NSString*)url; //建立viewController的時候初始化url - (IBAction)goBack:(id)sender; //返回 - (IBAction)goForward:(id)sender; //前進 - (IBAction)reload:(id)sender; //刷新 @property (retain, nonatomic) IBOutlet UIWebView *webView; @end
UIWebView的loadRequest方法能夠加載一個url地址,須要把url地址變成NSURLRequest參數atom
- (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:_url]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [_webView loadRequest:request]; self.title = @"正在加載"; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; //風火輪 }
3個方法的實現lua
- (IBAction)goBack:(id)sender{ if ([_webView canGoBack]) { [_webView goBack]; } } - (IBAction)goForward:(id)sender{ if ([_webView canGoForward]) { [_webView goForward]; } } - (IBAction)reload:(id)sender{ [_webView reload]; }
實現協議方法,加載成功和加載失敗後調用的方法url
#pragma mark - WebView Delegate - (void)webViewDidFinishLoad:(UIWebView *)webView{ [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; //關閉風火輪 NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];//解析JS代碼 self.title = title; } - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{ UIAlertView *alterview = [[UIAlertView alloc] initWithTitle:@"" message:[error localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil]; [alterview show]; [alterview release]; }
總結:瞭解了webView所須要的參數,加載過程,以及須要實現的協議方法spa