从Nib或Storyboard在WKWebView上设置WKWebViewConfiguration

问题描述 投票:9回答:4

在iOS 11中,Apple在你的笔尖和故事板上添加了添加WKWebViews插座的功能集。当使用自动设置的默认WKWebViewConfiguration时,它似乎工作正常。

但是,我希望能够使用自定义WKWebViewConfiguration。无论如何我可以在之前,或者从nib初始化WKWebView之后设置它吗?

ios uiwebview interface-builder wkwebview
4个回答
4
投票

让我们举例说明您的自定义配置。

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

//Here you can customize configuration
[self.webView.configuration.userContentController addUserScript:wkUScript];

// self.webView.navigationDelegate = self;
// self.webView.contentMode = UIViewContentModeScaleAspectFill;

3
投票

您可以在Storyboard中创建WKWebView,然后使用WKUIDelegate:createWebViewWith创建仅具有配置的新WKWebView。

class WindowViewController: UIViewController {

    // The WKWebView created from storyboard
    @IBOutlet var webView: WKWebView!

    override func viewDidLoad() {

        // Delegate the webview's uiDelegate
        self.webView.uiDelegate = self
    }
}

extension WindowViewController: WKUIDelegate {

    func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {

        // Create new WKWebView with custom configuration here
        let configuration = WKWebViewConfiguration()

        return WKWebView(frame: webView.frame, configuration: configuration)
    }
}

0
投票

由于WKWebView的配置属性是只读的,因此无法通过故事板中的WKWebView插座设置WKWebView的配置,而是需要以编程方式配置如下所示。

class ViewController: UIViewController {

    @IBOutlet weak var webContentView: UIView!
    var webView: WKWebView?

    let contentController = WKUserContentController()        
    contentController.add(self, name: "callbackHandler")

    let configuration = WKWebViewConfiguration()
    configuration.userContentController = contentController

    self.webView = WKWebView(frame: self.webContentView.bounds, configuration: configuration)
    self.webContentView.addSubview(self.webView!)
}

并实现WKScriptMessageHandler委托方法

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    if (message.name == "callbackHandler"){
        print("\(message.body)")
    }
}

希望这可以帮助...


0
投票

是!!!我们可以从Nib或Storyboard在WKWebView上设置WKWebViewConfiguration我使用下面的代码:

这是我的IBOutlet--

 @IBOutlet  var webViewChat: WKWebView!

//使用以下代码可以设置配置

 webViewChat.configuration.userContentController.add(self, name: "edit")
 webViewChat.configuration.userContentController.add(self, name: "remove")

注意:确保在设置配置后加载URL

© www.soinside.com 2019 - 2024. All rights reserved.