你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS學習之WebView的使用

iOS學習之WebView的使用

編輯:IOS開發綜合

1、初始化WebView

- (void)viewDidLoad
{
[super viewDidLoad];
webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
NSURLRequest *request =[NSURLRequest requestWithURL:[NSURL URLWithString:@http://www.baidu.com]];
[self.view addSubview: webView];
[webView loadRequest:request];
}

2、

實現協議,在ViewController.h修改如下

#import


@interface ViewController : UIViewController
{
UIWebView *webView;
}
@end

UIWebView中幾個重要的函數
1.- (void )webViewDidStartLoad:(UIWebView *)webView 網頁開始加載的時候調用
2.- (void )webViewDidFinishLoad:(UIWebView *)webView 網頁加載完成的時候調用
3.- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error 網頁加載錯誤的時候調用

先在viewDidLoad 的webView實例化下面加上

[webView setDelegate:self];設置代理。這樣上面的三個方法才能得到回調。

 

3、加載等待頁面

- (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];
}

加載完成或失敗時,去掉loading效果

- (void) webViewDidFinishLoad:(UIWebView *)webView
{
[activityIndicator stopAnimating];
UIView *view = (UIView*)[self.view viewWithTag:108];
[view removeFromSuperview];
NSLog(@webViewDidFinishLoad);


}
- (void) webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[activityIndicator stopAnimating];
UIView *view = (UIView*)[self.view viewWithTag:108];
[view removeFromSuperview];

}

 

 


 

  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved