1.創(chuàng)建wkwebview
- (instancetype)initWithFrame:(CGRect)frame configuration:(WKWebViewConfiguration *)configuration NS_DESIGNATED_INITIALIZER;
webview基于UIScrollView父類浴捆,
_webview.scrollView.bounces = NO; //如果是烦秩,則跳過內(nèi)容的邊緣并再次返回
WKUIDelegate,WKScriptMessageHandler,WKNavigationDelegate,設置三個代理
2.//遵守代理
_webview.UIDelegate = self;
_webview.navigationDelegate = self;
3.//設置WKWebViewConfiguration
_wkConfig = [[WKWebViewConfiguration alloc] init];
_wkConfig.userContentController = [[WKUserContentController alloc] init];
往其中加入一些js代碼箱舞,防止字體變小或者變大
NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
? ? ? ? WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
? ? ? ? [_wkConfig.userContentController addUserScript:wkUScript];
//與H5交互添加相對應的方法
[_wkConfig.userContentController addScriptMessageHandler:self name:@"方法名"];
//設置h5頁面的最小字體
?_wkConfig.processPool = [[WKProcessPool alloc] init];
? ? ? ? WKPreferences *preferences = [WKPreferences new];
?? ? ? ? ? preferences.javaScriptCanOpenWindowsAutomatically = YES;
?? ? ? ? ? //設定最小字體
?? ? ? ? ? preferences.minimumFontSize= 13.0;
? ? ? ? _wkConfig.preferences= preferences;
//響應H5調(diào)用的方法
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
//回傳給H5數(shù)據(jù)
- (void)webView:(WKWebView*)webView didFinishNavigation:(WKNavigation*)navigation
{
? ? NSString *jsStr = @"var awsdk = new Object();";
? ? NSLog(@"jsStr===%@",jsStr);
? ? dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
? ? ? ? [self.webview evaluateJavaScript:jsStr completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
? ? ? ? ? ? NSLog(@"JS回調(diào):-sss- %@? %@", obj, error);
? ? ? ? }];
? ? });
}