通过url加载(代理方式)
#import "ViewController.h"
@interface ViewController ()<UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *webView;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.webView.delegate = self;
//通过一个url,加载一个网页
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.jianshu.com"]]];
//页面内容自适应整个屏幕大小
self.webView.scalesPageToFit = YES;
//设置边距
self.webView.scrollView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
}
//返回
- (IBAction)goBack:(UIBarButtonItem *)sender {
[self.webView goBack];
}
//前进
- (IBAction)goForward:(UIBarButtonItem *)sender {
[self.webView goForward];
}
//刷新
- (IBAction)refresh:(UIBarButtonItem *)sender {
[self.webView reload];
}
#pragma mark -
#pragma mark - <UIWebViewDelegate>
//已经开始加载
-(void)webViewDidStartLoad:(UIWebView *)webView{
NSLog(@"开始加载了");
}
//已经完成加载
- (void)webViewDidFinishLoad:(UIWebView *)webView{
//设置前进、后退按钮的点击
self.backItem.enabled = webView.canGoBack;
self.forwardItem.enabled = webView.canGoForward;
}
//加载出现错误
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
self.backItem.enabled = webView.canGoBack;
self.forwardItem.enabled = webView.canGoForward;
}
/*
*每当webView即将发送请求之前,都会调用这个方法
*返回YES:允许加载这个请求
*返回NO:禁止加载这个请求
*/
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
if([request.URL.absoluteString containsString:@"2015"]) return NO;
return YES;
}
通过本地路径加载
//[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:@"/Users/mac1/Desktop/IOS.pdf"]]];
通过HTML字符串加载
//[self.webView loadHTMLString:@"<html><body><div style=\"color: red; font-size:40px; \">简书</div></body></html>" baseURL:nil];
通过html文件加载
// 检测各种特殊的字符串:比如电话、网站等,效果为加下划线,长按有响应的操作
self.webView.dataDetectorTypes = UIDataDetectorTypeAll;
[self.webView loadRequest:[NSURLRequest requestWithURL:[[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"]]];