The required initializer is not the right one -- because your class is a subclass of UIViewController
, you need a required init?(coder: NSCoder)
. You can put your custom initializer that sets backgroundColor
in separate init
.
Also, instead of viewDidLoad
, use loadView
for your custom View Controllers that you make in code. This is how you do it:
class UIViewControllerModel: UIViewController {
var backgroundColor: UIColor
/// Put your custom argument labels here, not inside the `required init?`
init(backgroundColor: UIColor) {
self.backgroundColor = backgroundColor
super.init(nibName: nil, bundle: nil)
}
/// This is in case the View Controller is loaded from the Storyboard
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Use this instead of viewDidLoad
override func loadView() {
/**
Instantiate the base `view`.
*/
view = UIView()
view.backgroundColor = backgroundColor
}
}
let modelVC = UIViewControllerModel(backgroundColor: UIColor.blue)
self.present(modelVC, animated: true)
Result:
