How to Write Init Methods of a Uiviewcontroller in Swift

how to init() a swift view controller properly?

Initialization depends on a couple of condition.

  1. If you are using storyboard, you can just remove the init and your VC will have default initializer. Make sure either all of your properties have default value or they are optional.
  2. If you are using xib or just creating view programmatically you can have custom convenience initializer where you pass some extra data this way.
class MyViewController: ViewController {
var answer: Int
convenience init(answer: Int) {
self.init()

self.answer = answer
// Do other setup
}
}

How can I initialize a variable for UIViewController class in right syntax?

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:

View controller with blue background presented

How do I make a custom initializer for a UIViewController subclass in Swift?

class ViewController: UIViewController {

var imageURL: NSURL?

// this is a convenient way to create this view controller without a imageURL
convenience init() {
self.init(imageURL: nil)
}

init(imageURL: NSURL?) {
self.imageURL = imageURL
super.init(nibName: nil, bundle: nil)
}

// if this view controller is loaded from a storyboard, imageURL will be nil

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

Write init method to pass model to view controller before viewDidLoad]

Unfortunately there's no way to do this with storyboards as view controllers are initialized beforehand.

I wrote a post on making view controller and view model associations more explicit though.



Related Topics



Leave a reply



Submit