- 背景故事:
项目中涉及到一个html的页面.
wkwebview加载的web页面.
需要
“在web中点击返回主页按钮时,返回到原生主页,而非web主页”
2018年一月2号的我还不懂html5和h5与原生的交互.
尝试了很多方法....首先,html5 网站的代码是不能改的...javascript也没有预留和ios交互的接口...里面的页面转换也不能用wkwebview的delegate拦截到...
于是想了一个我自己感觉有点笨的方法...
思路是用UITouch来控制webview的点击事件,每次点击之后过0.5s(留出页面转换的事件)去获取当前的url,如果url是web主页的url就返回到原生主页..
代码如下:
先创建一个名为CustomWKWebView的子类,.h文件如下
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
static UIEvent *e = nil;
if (e != nil && e == event) {
e = nil;
return [super hitTest:point withEvent:event];
}
e = event;
if (event.type == UIEventTypeTouches) {
NSSet *touches = [event touchesForView:self];
UITouch *touch = [touches anyObject];
if (touch.phase == UITouchPhaseBegan) {
NSLog(@"Touches began");
NSLog(@"%@",self.URL.absoluteString);
[self performSelector:@selector(delayMethod)
withObject:nil
afterDelay:0.5f];
}else if(touch.phase == UITouchPhaseEnded){
NSLog(@"Touches Ended");
}else if(touch.phase == UITouchPhaseCancelled){
NSLog(@"Touches Cancelled");
}else if (touch.phase == UITouchPhaseMoved){
NSLog(@"Touches Moved");
}
}
return [super hitTest:point withEvent:event];
}
-(void)delayMethod
{
NSLog(@"%@",self.URL.absoluteString);
if ([self.URL.absoluteString isEqualToString:@"主页的url"]) {
[[NSNotificationCenter defaultCenter] postNotificationName:@"wkwebview-backtohome" object:nil];
}
}
网友评论