UI控件---UIWebView
UIWebView是内置浏览器控件,可以用来浏览网页,文档等,今天就试着做一个简易的浏览器!
定义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参数
- (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:_url]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [_webView loadRequest:request]; self.title = @"正在加载"; [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; //风火轮 }
3个方法的实现
- (IBAction)goBack:(id)sender{ if ([_webView canGoBack]) { [_webView goBack]; } } - (IBAction)goForward:(id)sender{ if ([_webView canGoForward]) { [_webView goForward]; } } - (IBAction)reload:(id)sender{ [_webView reload]; }
实现协议方法,加载成功和加载失败后调用的方法
#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所需要的参数,加载过程,以及需要实现的协议方法