如果只是简单的使用 webview ,其实很简单,至于优化的话,可能就比较麻烦。
先上效果图:
1. 新建一个 singleview 项目,然后将必要的webview和其他一些控件拖到storyboard的界面上。
2. 选中 webview ,右键,将它的 delegate 与 controller 连接,因为等下要实现 webview 的一些代理方法。
(当然也可以在程序中,用代码将controller赋值给 webview的delegate,实现效果一样。例如:self.webview.delegate = self; )
3. 要 webview 加载某个网页或者是静态HTML页面,方法有三个:
- (void)loadRequest:(NSURLRequest *)request;
- (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL;
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;
4. 代理方法有:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
- (void)webViewDidStartLoad:(UIWebView *)webView;
- (void)webViewDidFinishLoad:(UIWebView *)webView;
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;
以下是我的代码:
- (IBAction)jumpBtnClick:(UIButton *)sender
{
NSURL *url = [NSURL URLWithString:[self.urlTF text]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
- (IBAction)reloadBtnClick:(UIButton *)sender
{
[self.webView reload];
NSLog(@"重新加载");
}
- (IBAction)stopLoadBtnClick:(UIButton *)sender
{
[self.webView stopLoading];
NSLog(@"停止加载");
}
- (IBAction)goBackBtnClick:(UIButton *)sender
{
[self.webView goBack];
NSLog(@"返回");
}
- (IBAction)goForwardBtnClick:(UIButton *)sender
{
[self.webView goForward];
NSLog(@"前进");
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@"加载网页失败: %@", error);
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"网页加载完成");
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(@"开始加载网页");
}