Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
    }
    ・・・・・・
}
like image 944
Jing Bian Avatar asked Dec 05 '25 05:12

Jing Bian


1 Answers

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)
like image 112
Andreas Oetjen Avatar answered Dec 07 '25 20:12

Andreas Oetjen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!