1

Problem:

I'm having trouble setting an instance variable when I return to the main view controller from a secondary view controller.

Setup:

My main view controller has a UIButton associated with a Show segue to a second view controller. This second view controller has a collection view (it's a calendar) that triggers a Show segue to the original view controller. I am trying to set a variable in the first view controller with prepare(for segue:) called in the second view controller. No dice.

Code:

Main View Controller:

class ViewController: UIViewController {
    var myDate=Date()

    func viewDidAppear(): {
        updateDateLabel(myDate)
    }
    ...
}

Calendar (second) View Controller:

class CalendarViewController: UIViewController {
    var selectedDate: Date?

    func calendar(..., didSelectDate date: Date, ...) {
        selectedDate = date
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "dateSelected" {
            let vc = segue.destination as! ViewController
            vc.myDate = self.selectedDate
        }
    }

I suspect my main view controller is reinitializing the myDate variable, but how do I address this?

BenJ
  • 187
  • 1
  • 14
  • Possible duplicate of [Passing data with unwind segue](https://stackoverflow.com/questions/35313747/passing-data-with-unwind-segue) – rbaldwin May 09 '18 at 19:52
  • You can put an `unwind Segue` function in your main VC, and perform that unwind Segue in your second VC to go back. There you can update myDate with the selectedDate from your Calendar VC. There are many examples on SO and the web on how to do this. – rbaldwin May 09 '18 at 19:56
  • This is the answer. Thanks @rbaldwin! – BenJ May 10 '18 at 02:47

1 Answers1

0

No, main view controller will not reinitializing the myDate

You have created myDate in a wrong way, Please create like this way:

var myDate: Date?

Or

var myDate = Date()
Jogendar Choudhary
  • 3,476
  • 1
  • 12
  • 26