如何使UIWebView響應Touch事件

    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;
}


原文地址:http://apps.hi.baidu.com/share/detail/40317282

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章