UIWebView主要有三种方法实现页面的装载,分别是:
1. (void)loadRequest:(NSURLRequest *)request; (直接装载URL)
2. (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL; (主要用于装载用字符串拼接成的HTML代码)
3 .(void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)textEncodingName baseURL:(NSURL *)baseURL;(主要应用于转载本地页面或者外部传来的NSData)
UIWebViewDelegate协议中的方法
//准备加载内容时调用的方法
- (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;
下面实现直接在在手机页面上加载淘宝网(直接装载URL)
#import "MyWebViewController.h"
//需要添加UIWebViewDelegate协议
@interface MyWebViewController ()<UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *myWebView;
@end
@implementation MyWebViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
//调用该方法
[self createMyWebView];
}
//创建WebView
- (void)createMyWebView{
//初始化并设置myWebView的frame
_myWebView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//设置代理
_myWebView.delegate = self;
_myWebView.delegate = self;
//自动对页面进行缩放以适应屏幕
_myWebView.scalesPageToFit = YES;
//加载网络资源
//创建URL
NSURL *url = [NSURL URLWithString:@"https://www.taobao.com/"];
//创建NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//加载
[_myWebView loadRequest:request];
//将_myWebView添加到view
[self.view addSubview:_myWebView];
}