UIWebView 的基本用法

一、创建UIWebView

CGRect bouds = [[UIScreen manScreen]applicationFrame];  

UIWebView* webView = [[UIWebView alloc]initWithFrame:bounds];

[self.view addSubview:webView]; 


二. 属性

webView.scalesPageToFit = YES ;//设置自适应屏幕


三.webView 3种加载方式

1、直接给出url地址即可将web content载入。

NSString *path = @"http://m.jumei.com/";

    NSURL *url = [[NSURL alloc] initWithString:path];

    [_webView loadRequest:[NSURLRequest requestWithURL:url]];


2、将本地html文件内容嵌入webView

(1)无脚本

    NSString *html = @"hello <h1>world<h1>";

(2)含有js脚本的

    NSString *html = @"<script language='javascript'>alert('hello');</script>'";

    [_webView loadHTMLString:html baseURL:nil];

(3)加载本地存在的html文件

    NSString *resourcePath = [ [NSBundle mainBundle] resourcePath];

    NSString *filePath  = [resourcePath stringByAppendingPathComponent:@"my.html"];

    NSString *htmlstring =[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    [_webView loadHTMLString:htmlstring  baseURL:[NSURL fileURLWithPath: [[NSBundle mainBundle]  bundlePath]]];


3、将本地html文件内容嵌入webView 更详细的给出了web content的编码方式。

    NSBundle *bundle = [NSBundle mainBundle];

    NSString *path = [bundle pathForResource:@"my" ofType:@"html"];

    //word.html存在工程的资源目录中

    NSData *data = [[NSData alloc]initWithContentsOfFile:path];

    [_webView loadData:data MIMEType:nil textEncodingName:nil baseURL:nil]


四.UIWebView 代理方法

先设置_webView.delegate = self;


当网页视图被指示载入内容而得到通知。应当返回YES

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


五.界面动作

[webView goBack]; //返回   

[webView goForward];//向前    

[webView reload];//重载     

[webView stopLoading];//取消载入内容 




你可能感兴趣的:(ios,UIWebView)