I am trying to segue from first viewcontroller to the second one and pass the value of var dateAndTime = NSDate()
to the second view controller.
My first approach was to segue from the first viewcontroller itself to the second one, define the name of the segue in Attributes inspector.
Next, I link a button @IBAction func nextButtonToFifthViewController
in the first viewcontroller, use an if else
statement and prepareForSegue
, but the code does not compile because I am not allowed to override prepareForSegue
.
@IBAction func nextButtonToFifthViewController(sender: AnyObject) {
if timeRestricted.contains(hourComponents){
self.label.text = "Please choose a time betwen 7:00 - 19:00"
} else {
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var destViewController:FifthViewController = segue.destinationViewController as! FifthViewController
destViewController.dateAndTimeSelected = dateAndTime }
}
My second approach was to use performSegueWithIdentifier
, but I wont be able to pass data to the next view controller because dateAndTimeSelected
is not available for use in first view controller.
@IBAction func nextButtonToFifthViewController(sender: AnyObject) {
if timeRestricted.contains(hourComponents){
self.label.text = "Please choose a time betwen 7:00 - 19:00"
} else {
performSegueWithIdentifier("toFifthViewController", sender: self)
dateAndTimeSelected = dateAndTime
}
Note that performSegueWithIdentifier
and prepareForSegue
methods should be used together. First you call performSegueWithIdentifier
when you already sure that you need move to new view controller, then you may configure your new view controller in prepareForSegue
@IBAction func nextButtonToFifthViewController(sender: AnyObject) {
if timeRestricted.contains(hourComponents){
self.label.text = "Please choose a time betwen 7:00 - 19:00"
} else {
performSegueWithIdentifier("toFifthViewController", sender: self)
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "toFifthViewController" {
if let destViewController = segue.destinationViewController as? FifthViewController {
destViewController.dateAndTimeSelected = dateAndTime
}
}
}