Ethan Zhao
Ethan Zhao

Reputation: 249

Xcode 8: How to pass data to a view controller without using a segue or storyboard?

So I have this code that instantiates a view controller when a button is pressed:

@IBAction func addChapter(_ sender: Any) {
    let addChapterController = AddChapterViewController()
    self.present(addChapterController, animated: true, completion: nil)
}

Without a prepareForSegue, how do I pass data to this newly created view controller?

Upvotes: 0

Views: 2290

Answers (1)

Alexandre Lara
Alexandre Lara

Reputation: 2568

In your AddChapterViewController you can create the variables that you want to change, for example:

class AddChapterViewController: UIViewController{
    var name: String?
    var id: Int?
    // ....
}

So you can use its properties now like this:

@IBAction func addChapter(_ sender: Any) {
    let addChapterController = AddChapterViewController()
    addChapterController.name = "Name example"
    addChapterController.id = 10

    self.present(addChapterController, animated: true, completion: nil)
}

Upvotes: 5

Related Questions