3

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()
    }
    ・・・・・・
}
0

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.