xml2.html
<html>
<head>
<h1>我是大标题</h1>
<h2>我是二标题</h2>
<hr>
</head>
<body>
<script>
function func(){
//document.write("<p>灰常不错</p>");
alert("天气依然很好!");
}
function func2(){
window.location.href="oc://ocFunc"
}
</script>
<p>今天星期日,晴空万里,雷电交加。</p>
<a href="http://www.baidu.com">百度</a>
<button onclick="func2()">点我</button>
</body>
</html>
#import "ViewController.h"
@interface ViewController ()<UIWebViewDelegate>
{
UIWebView *_webView;
UITextField *_textField;
}
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//地址栏
_textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 20, 320, 20)];
_textField.borderStyle = UITextBorderStyleRoundedRect;
[self.view addSubview:_textField];
NSArray *array = @[@"转到",@"前进",@"后退",@"刷新",@"停止",@"html",@"调js"];
for (int i = 0; i < array.count; i++) {
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(i * (320 / array.count), 40, 320/array.count, 20);
[button setTitle:array[i] forState:UIControlStateNormal];
button.tag = i;
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:button];
}
_webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 60, 320, 420)];
_webView.delegate = self;
[self.view addSubview:_webView];
}
-(void)buttonClick:(UIButton *)btn
{
if (btn.tag == 0) {
//添加前缀
if (![_textField.text hasPrefix:@"http"]) {
_textField.text = [NSString stringWithFormat:@"http://%@",_textField.text];
}
NSURLRequest *reqeust = [NSURLRequest requestWithURL:[NSURL URLWithString:_textField.text]];
//webView 加载请求
[_webView loadRequest:reqeust];
[_textField resignFirstResponder];
}
//前进
if (btn.tag == 1) {
[_webView goForward];
}
//后退
if (btn.tag == 2) {
[_webView goBack];
}
//刷新
if (btn.tag == 3) {
[_webView reload];
}
//停止
if (btn.tag == 4) {
[_webView stopLoading];
}
//加载本地html
if (btn.tag == 5) {
NSString *path = [[NSBundle mainBundle] pathForResource:@"xml2" ofType:@"html"];
NSString *htmlStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//加载本地html
[_webView loadHTMLString:htmlStr baseURL:nil];
}
/*
js调用oc代码:
oc调用js代码: stringByEvaluatingJavaScriptFromString:
*/
if (btn.tag == 6) {
[_webView stringByEvaluatingJavaScriptFromString:@"func()"];
}
//js调用oc
}
-(void)ocFunc
{
NSLog(@"我是大oc");
}
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//更新地址
_textField.text = request.URL.absoluteString;
//js调oc
/*
js发起一个非法地址请求,oc截取到,解析地址,拿到要调用的方法名称,进行方法调用
oc://ocFunc
*/
NSArray *array = [request.URL.absoluteString componentsSeparatedByString:@"://"];
if ([array[0] isEqualToString:@"oc"]) {
SEL sel = NSSelectorFromString(array[1]);
[self performSelector:sel];
}
return YES;
}