
QQ20180103-171731-HD.gif
解決辦法
就是用 WKWebView 代替 UIWebView WKWebView在各個(gè)性能都要比UIWebView高, 這是個(gè)不錯(cuò)的選中, 事實(shí)證明, 我的選擇也是正確的.如果你僅僅是為了解決現(xiàn)實(shí)的問題, 那么你就換成WKWebView.
下面我就要說我遇到的其他問題. 因?yàn)槲也恢宫F(xiàn)實(shí)的問題 , 我的還需要點(diǎn)擊圖片放大, 所以得加攔截到點(diǎn)擊事件.
- 添加點(diǎn)擊事件, 需要后臺(tái)加點(diǎn)擊的標(biāo)簽, 然后我們?nèi)r截標(biāo)簽, 這是一種方法,
2 自己給這個(gè)忘記植入 JS 代碼.
因?yàn)槲覀兒笈_(tái)設(shè)置的這個(gè)圖片用通過富文本編輯, 所以不好加標(biāo)簽, 后臺(tái)本來也可以植入 JS 代碼的, 但是也是因?yàn)樯厦孢@個(gè)原因 不能加. 所以就只能我們這邊植入 JS 代碼了 .在原來用UIWebView 也是我們這邊植入的JS 代碼. 但是換成 WKWebView 再次植入的代碼就不行了
// 頁面加載完成之后調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
//js方法遍歷圖片添加點(diǎn)擊事件 返回圖片個(gè)數(shù)
static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
for(var i=0;i<objs.length;i++){\
objs[i].onclick=function(){\
document.location=\"myweb:imageClick:\"+this.src;\
};\
};\
return objs.length;\
};";
DLog(@"%@",jsGetImages);
[webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"value: %@ error: %@", response, error);
}];
}
于是就上網(wǎng)找了找相關(guān)的一些文章.大多數(shù)都是沒有提到的,找了很久, 嘗試了很多種方法都不行,于是我就把實(shí)例化的方式改變了之前是
- (WKWebView *)mainWeb
{
if (!_mainWeb) {
_mainWeb = [[WKWebView alloc]initWithFrame:CGRectMake(0, NavHeight, ScreenWidth, ScreenHeight - NavHeight)];
_mainWeb.navigationDelegate = self;
_mainWeb.UIDelegate = self;
[self.view addSubview:_mainWeb];
}
return _mainWeb;
}
換成了下面這種
- (WKWebView *)mainWeb
{
if (!_mainWeb) {
// 根據(jù)JS字符串初始化WKUserScript對(duì)象
static NSString * const jsGetImages =
@"function getImages(){\
var objs = document.getElementsByTagName(\"img\");\
for(var i=0;i<objs.length;i++){\
objs[i].onclick=function(){\
document.location=\"myweb:imageClick:\"+this.src;\
};\
};\
return objs.length;\
};";
WKUserScript *script = [[WKUserScript alloc] initWithSource:jsGetImages injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
//
// // 根據(jù)生成的WKUserScript對(duì)象,初始化WKWebViewConfiguration
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config.userContentController addUserScript:script];
_mainWeb = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - TabbarHeight)configuration:config];
_mainWeb.navigationDelegate = self;
_mainWeb.UIDelegate = self;
[self.view addSubview:_mainWeb];
}
return _mainWeb;
}
果然黃天不負(fù)有心人呀, 花了大半天的時(shí)間終于找到了原因, 就是要在WKWebView 實(shí)例化的時(shí)候 也要植入 JS 代碼, 這樣就可以點(diǎn)擊圖片的時(shí)候就能走下面的方法了.
000D949B-FC46-4877-867D-3FCD00971989.png