Ben
Ben

Reputation: 4867

WebKitView not adhering to auto layout rules

I'd like to place a WKWebView in a UIView, with some padding around. Let's say 50 pixels. Here's what this looks like in Interface Builder:

Interface builder screenshot

Unfortunately the app doesn't behave as expected when run:

Simulator screenshot

Here is the code:

import UIKit
import WebKit

class ViewController: UIViewController {
    @IBOutlet var webView: WebView!
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let url = "http://apple.com"
        webView.loadUrl(string: url)
    }
}
class WebView: WKWebView {
    required init?(coder: NSCoder) {
        if let _view = UIView(coder: coder) {
            super.init(frame: _view.frame, configuration: WKWebViewConfiguration())
            autoresizingMask = _view.autoresizingMask
        } else {
            return nil
        }
    }
    func loadUrl(string: String) {
        if let url = URL(string: string) {
            load(URLRequest(url: url))
        }
    }
}

What might cause this kind of issue, and how might I fix it?

Many thanks in advance!

Upvotes: 0

Views: 39

Answers (1)

Faipdeoiad
Faipdeoiad

Reputation: 122

Since you're setting this in Storyboard just remove the required init?(coder: NSCoder)

or use:

   required init?(coder: NSCoder) {
        super.init(coder: coder)
    }

Upvotes: 1

Related Questions