UIWebView響應不了Touch事件,很久以前就很難解決。最後有一個叫做UICWebView的東西,雖然用了private api,但是可以用。不過----UICWebView或者任何用UIWebDocumentView獲得事件的方法在iOS4 100%會出錯(因爲UIWebDocumentView這個東西沒了)。用下面的方法可以讓UIWebView響應Touch事件,而且不會影響滾動拖拽的bouncing。
如果需要touch的個數或者座標,也很簡 單,不過需要自己修改代碼裏的JavaScript。
- (void)viewDidLoad {
[super viewDidLoad];
self.webView.delegate=self;
NSString *resourcePath = [ [NSBundle mainBundle] resourcePath];
NSString *filePath = [resourcePath stringByAppendingPathComponent:@"test.html"];
NSString *htmlstring = [[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSString *newHTMLString =
[htmlstring stringByAppendingString:
@"<script language=\"javascript\">
document.ontouchstart =
function(){
document.location=\"myweb:touch:start\";
};
document.ontouchend =
function(){
document.location=\"myweb:touch:end\";
};
document.ontouchmove =
function(){
document.location=\"myweb:touch:move\";
}
</script>"
];
[self.webView loadHTMLString:newHTMLString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
[htmlstring release];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *requestString = [[request URL] absoluteString];
NSArray *components = [requestString componentsSeparatedByString:@":"];
if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"myweb"]) {
if([(NSString *)[components objectAtIndex:1] isEqualToString:@"touch"]) {
NSLog(@"%@",[components objectAtIndex:2]);
}
return NO;
}
return YES;
}