一、UIWebView 可以加载和显示某个URL的网页,也可以显示基于HTML的本地网页或部分网页:
a. 加载 URL
- WebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 44, 320, 400)];
- NSString *path = @"http://www.baidu.com";
- NSURL *url = [NSURL URLWithString:path];
- [WebView loadRequest:[NSURLRequest requestWithURL:url]];
b. 加载 HTML
NSString *resPath = [bundle resourcePath];
NSString *filePath = [resPath stringByAppendingPathComponent:@"Home.html"];
[webView loadHTMLString:[NSString stringWithContentsOfFile:filePath]
baseURL:[NSURL fileURLWithPath:[bundle bundlePath]]];
二、使用网页加载指示,加载完成后再显示网页出来
首先要指定委托方法:
webView.delegate =self;
UIWebView主要有下面几个委托方法:
1、- (void)webViewDidStartLoad:(UIWebView *)webView;开始加载的时候执行该方法。
2、- (void)webViewDidFinishLoad:(UIWebView *)webView;加载完成的时候执行该方法。
3、- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error;加载出错的时候执行该方法。
这样,可以利用 webViewDidStartLoad 和 webViewDidFinishLoad 方法实现本功能:
- - (void) webViewDidStartLoad:(UIWebView *)webView
- {
- //创建UIActivityIndicatorView背底半透明View
- UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
- [view setTag:108];
- [view setBackgroundColor:[UIColor blackColor]];
- [view setAlpha:0.5];
- [self.view addSubview:view];
- activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
- [activityIndicator setCenter:view.center];
- [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
- [view addSubview:activityIndicator];
- [activityIndicator startAnimating];
- }
- - (void) webViewDidFinishLoad:(UIWebView *)webView
- {
- [activityIndicator stopAnimating];
- UIView *view = (UIView*)[self.view viewWithTag:108];
- [view removeFromSuperview];
- NSLog(@"webViewDidFinishLoad");
- }
三、UIWebView还可以通过 stringByEvaluatingJavaScriptFromString 函数来执行 javascript代码,从而可以更加灵活地处理网页文件
1. 获得UIWebView的标题
NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"];
2. 获取页面的URL
NSString *currentURL = [webView stringByEvaluatingJavaScriptFromString:@"document.location.href"];
3. 修改页面元素的值
NSString *js_result = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByName('q')[0].value='朱祁林';"];
4. 表单提交
5. 字体颜色:
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextFillColor= 'white'"];
6. 背景颜色:
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.backgroundColor = 'black';"];
7. 文本大小:
[webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '80%'"];
四、综合运用以上方法,还可以实现部分网页的显示,基本思路如下:
1. 用 loadRequest 先获取网页,但先设置 UIWebView.hidden = YES;
2. 在 webViewDidFinishLoad 中,用