Search code examples
swiftios8xcode6popoveruidatepicker

How can I use the selected data from a UIDatePicker in another view in IOS8?


I'm very new to IOS 8 and programming in general. I would like to populate a UIButton's label text with the value from a UIDatePicker. When the user presses the button, a popover appears with a date picker. I have created a new view controller imbedded in a navigation controller for my date picker. They are connected using a popover segue. My question is once the user selects a date, how can I transmit this information back to the original view controller to show the value on the button label. Any help would be greatly appreciated.


Solution

  • To pass a value between 2 viewcontrollers using segues is easies done like this:

    class VC1:UIViewController {
        @IBAction func next() {
            let valueToPass = NSDate() // Could be anything that conforms to AnyObject
            self.performSegueWithIdentifier("segueID", sender: valueToPass) // Use this method unless you're connecting a button to a viewcontroller in storyboard
        }
    
        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            let vc2 = segue.destinationViewController as VC2 // The viewcontroller you're going to
            vc2.date = sender as NSDate // If you connected button to vc in storyboard sender will be nil, so in that case just set the vc2.date directly here
        }
    }
    
    
    class VC2:UIViewController {
        var date:NSDate! // Property you want to pass to
    }