Jing Bian
Jing Bian

Reputation: 505

about initializing of viewcontroller (swift)

I have a ViewController file called TwoViewController.swift and a nib file called TwoViewController.xib.

TwoViewController.swift like this ↓

class TwoViewController: UIViewController {
    var pageTitle: String?

    ・・・・・・
    override func viewDidLoad() {
       super.viewDidLoad()
    }
    ・・・・・・
}

then, I would new a TwoViewController and present it at OneViewController.swift like this↓

class OneViewController: UIViewController {

    ・・・・・・
    override func viewDidLoad() {
       super.viewDidLoad()
    }
    ・・・・・・
    func presentTwo() {
       let two = new TwoViewController()
       two.pageTitle = "2222"
       self.present(two, animated: false, completion: nil)
    }
}

But, I want to new TwoViewController and set value to property pageTitle at the same time like this ↓ new TwoViewController(pageTitle: "22222")

To do that, I think I need create an init method at TwoViewController. I tried to make an init method like below↓. Is this correct?

class TwoViewController: UIViewController {
    var pageTitle: String

    init(pageTitle: String) {
       super.init(nibName: nil, bundle: nil)
       self.pageTitle = pageTitle
    }

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

    override func viewDidLoad() {
       super.viewDidLoad()
    }
    ・・・・・・
}

Upvotes: 3

Views: 6776

Answers (2)

Andreas Oetjen
Andreas Oetjen

Reputation: 10209

You could do so, but then you'd have to initialize pageTitle in every initializer with some default value, which you typically don't know.

Therefore, this is not quite common to do so. Instead assign the property value after initialization, like you did originally (in funcTwo), and go on with processing in viewDidLoad:

class TwoViewController: UIViewController {
    var pageTitle: String!

    override func viewDidLoad() {
        // use pageTitle to fill some outlet or so:
        self.title = pageTitle
    }
}

or make pageTitle an optional and check in viewDidLoad if it is set.


By the way: If you follow the naming scheme and name your XIB file like your view controller, you could use the implicit form:

let twoController = TwoViewController.init()

or explicitly

    let twoController = TwoViewController.init(nibName: "TwoViewController", bundle: nil)

Upvotes: 3

BEN MESSAOUD Mahmoud
BEN MESSAOUD Mahmoud

Reputation: 736

you should initialise your TwoViewController from your nib file like this :

let twoController = TwoViewController.init(nibName: "TwoViewController", bundle: nil)

then you can initialise your pageTitle like this :

twoController.pageTitle = "2222"

then you can present your twoViewController like this :

self.present(twoController, animated: false, completion: nil)

Upvotes: 1

Related Questions