S.Verma
S.Verma

Reputation: 199

How do I save the value of date picker into a variable?

I'm making a To-Do app and I want the value of the date picker as saved by the user into a variable so that I can print that variable in a tableView.

This is my datePicker code:

@IBOutlet weak var datePicker: UIDatePicker!

override func viewDidLoad() {
    super.viewDidLoad()

    datePicker.minimumDate = Date()
    datePicker.locale = Locale.current
    datePicker.setValue(UIColor.gray, forKeyPath: "textColor")

}

Upvotes: 0

Views: 2031

Answers (2)

J.Ren
J.Ren

Reputation: 76

Add follow code in viewDidLoad.

datePicker.addTarget(self, action: "dateChanged:",
        forControlEvents: UIControlEvents.ValueChanged)

Then get value in func dateChanged.

     func dateChanged(datePicker : UIDatePicker){

    let formatter = NSDateFormatter()
    //formatter
    formatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
    print(formatter.stringFromDate(datePicker.date))

    //there you get your label first
    //let label = ...
    label.text = formatter.stringFromDate(datePicker.date)
}

Upvotes: 0

Pierre Perrin
Pierre Perrin

Reputation: 435

You can add a specific target to you Picker in order to get a new value. For example :

@IBOutlet weak var datePicker: UIDatePicker!
    var selectedDate : Date?

    override func viewDidLoad() {
        super.viewDidLoad()


        self.datePicker.addTarget(self, action: #selector(self.storeSelectedRow), for: UIControlEvents.valueChanged)
    }

    func storeSelectedRow(){

        self.selectedDate = self.datePicker.date
    }

OR

With the storyboard: As you add you pickerView as a @IBOutlet you can add a @IBAction to your view controller and then get the date of your picker and store it to a variable.

Please see this example that pass the Picker Value to another ViewController https://drive.google.com/file/d/0B2RAeG6eqtvCbWp1VE5IZ0E2Vkk/view?usp=sharing

Upvotes: 1

Related Questions