Wkwebview in Interface Builder

WKWebView in Interface Builder

You are correct - it doesn't seem to work. If you look in the headers, you'll see:

- (instancetype)initWithCoder:(NSCoder *)coder NS_UNAVAILABLE;

which implies that you can't instantiate one from a nib.

You'll have to do it by hand in viewDidLoad or loadView.

Set WKWebViewConfiguration on WKWebView from Nib or Storyboard


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;

Configuring Interface Builder's new WKWebView object

So as it turns out, the WKWebView refuses to become active while there is an entitlements file in your project. In my case, I had the App Sandbox enabled with the following settings:

  • com.apple.security.network.server – YES
  • com.apple.security.files.user-selected.read-writeYES

Once deleting the entitlements file and removing it entirely from the project, the WKWebView began to work again.

Why WKWebView becomes nil?

You must call super.loadView() when you override loadView this way. This is why the WKWebView is nil.

The docs suggest not overriding loadView at all when using a storyboard/xib

If you use Interface Builder to create your views and initialize the view controller, you must not override this method.

You should move those 2 lines of code as the second thing in viewDidLoad

override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
webView.navigationDelegate = self
....
}

WKWebView does not appear in a custom UIView

I found a solution about my issue.

Initially I used contentView.addSubview(webView). contentView is at the first level of my xib, created automatically when I create a new xib.

To solve my problem, I created an UIView as a subview of the contentView directly in Interface Builder.
Then, in y code I added the web view as a subview of this new view and not from the contentView. And now it's ok.

So, in brief

  • the situation before : xib's contentView --> webView
  • The situation now : xib's contentView --> UIView --> webView

How to embed WKWebView inside custom UIView properly?

You want to initialize WKWebView like this (Swift 3.0):

webView = WKWebView(frame: viewForEmbeddingWebView.bounds, configuration: WKWebViewConfiguration())
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.viewForEmbeddingWebView.addSubview(webView)


Related Topics



Leave a reply



Submit