Reputation: 876
I'm working on a Swift app and running into a crazy odd problem. I have a simple storyboard view controller setup, it has 3 UIButtons
a UIImageView
and a UIView
(as a subview of the main view).
I want to programmatically add a WKWebView
to the UIView
.
Easy enough right? All of the above are in the Storyboard View, declared in the custom UIViewController
class and connected in IB. However at run time, everything is nil. This is a snippet of my code:
@IBOutlet var button1 : UIButton!;
@IBOutlet var button2 : UIButton!;
@IBOutlet var button3 : UIButton!;
@IBOutlet weak var containerForWebView: UIView!
var webView: WKWebView!
override func loadView()
{
}
override func viewDidLoad()
{
super.viewDidLoad()
displayWebPage()
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
}
override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
}
private func displayWebPage()
{
webView = WKWebView()
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.frame = CGRect(origin: CGPoint.zero, size: containerForWebView.frame.size)
webView.navigationDelegate = self
containerForWebView.addSubview(webView)
let url = URL(string: "https://www.google.com")!
webView.load(URLRequest(url: url))
}
When the code calls the displayWebPage()
method I break on the first line. In the debugger you can see all of the UIViewController
properties are nil. The IBOutlets are Nil and the _view variable of the UIViewController
itself is nil.
I don't understand why this is happening. Everything is pretty simple and easily connected. I never ran into this sort of issue in Objective-C. Any advice is appreciated!
Upvotes: 2
Views: 228
Reputation: 130102
Remove loadView
implementation. Do not override that method, always use viewDidLoad
instead.
If you override loadView
then you are responsible for creating controller's view and assigning it to self.view
.
Upvotes: 4