4 回答

TA貢獻1799條經驗 獲得超8個贊
先看一下Web中,我們給h1標簽添加一個onclick事件,讓它在被點擊之后,修改當前的url。
Web中的HTML代碼:
<html>
<head>
<script>
function getInfo(name)
{
window.location = "/getInfo/"+name;
}
</script>
</head>
<body>
<h1 onclick="getInfo('why')">Name</h1>
</body>
</html>
iOS中,先拖拽WebView,訪問localhost,然后通過WebView的委托事件監聽url跳轉操作,并且把跳轉截取下來。
也就是說,在onclick的時候,普通瀏覽器灰跳轉到那個url,但是在iOS的這個WebView里面,這個跳轉會被攔截,
用這種方式可以巧妙地實現JS調用iOS的原生代碼:
//
// DWViewController.m
// DareWayApp
//
// Created by why on 14-6-3.
// Copyright (c) 2014年 DareWay. All rights reserved.
//
#import "DWViewController.h"
@interface DWViewController ()
@property (weak, nonatomic) IBOutlet UIWebView *myWebview; // 主頁面
@end
@implementation DWViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// 適配iOS6的狀態欄
if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
_myWebview.frame = CGRectMake(0,20,self.view.frame.size.width,self.view.frame.size.height-20);
}
// 加載制定的URL
NSURL *url =[NSURL URLWithString:@"http://localhost"];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
[_myWebview setDelegate:self];
[_myWebview loadRequest:request];
}
// 網頁中的每一個請求都會被觸發
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
// 每次跳轉時候判斷URL
if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/why"])
{
NSLog(@"why");
return NO;
}
return YES;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

TA貢獻1963條經驗 獲得超6個贊
先看一下Web中,我們給h1標簽添加一個onclick事件,讓它在被點擊之后,修改當前的url。
Web中的HTML代碼:
<html>
<head>
<script>
function getInfo(name)
{
window.location = "/getInfo/"+name;
}
</script>
</head>
<body>
<h1 onclick="getInfo('why')">Name</h1>
</body>
</html>
- 4 回答
- 0 關注
- 780 瀏覽
添加回答
舉報