Set WKWebViewConfiguration on WKWebView from Nib o

2019-06-16 09:18发布

问题:

With iOS 11 Apple has added the ability set add WKWebViews outlets on your nibs and storyboards. It seems to work fine when using the default WKWebViewConfiguration that get set automatically.

However, I'd like to be able to use a custom WKWebViewConfiguration. Is there anyway I can set this before, or after the WKWebView gets initialized from the nib?

回答1:

Let's Example your customize configuration.

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;


回答2:

You can create WKWebView in Storyboard and then using WKUIDelegate:createWebViewWith for creating new WKWebView with configuration alone.

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


回答3:

It is not possible to set the configuration of the WKWebView through the outlet of WKWebView form the storyboard because the configuration property of the WKWebView is read only, instead we need to programmatically configure as given below.

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!)
}

And implement the WKScriptMessageHandler delegate method

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

Hope this helps...