iOS學習之WebView的使用

來源:互聯網
上載者:User

iOS學習之WebView的使用

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

}

 

 


 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.