Get selected Day from UIDatePicker alert

Hi developers im trying to get the date & time from UIDatePicker my UIDatePicker in on an alert

let myDatePicker: UIDatePicker = UIDatePicker()
        let loc = Locale(identifier: "Es_mx")
        //myDatePicker.timeZone = NSTimeZone.local
        myDatePicker.locale = loc

        let date = myDatePicker.date
        let components = Calendar.current.dateComponents([.hour, .minute, .year, .day, .month], from: date)
        let year = components.year!
        let day = components.day!
        let month = components.month!
        let hour = components.hour!
        let minute = components.minute!
       myDatePicker.frame = CGRect(x: 0, y: 15, width: 270, height: 200)
       let alertController = UIAlertController(title: "\n\n\n\n\n\n\n\n", message: nil, preferredStyle: UIAlertController.Style.alert)
       alertController.view.addSubview(myDatePicker)
       //let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
        let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default) { (somethingAction: UIAlertAction!) in
                       print("dia: \(day), mes: \(month), año: \(year), hora: \(hour), minuto: \(minute)")
            }


       let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil)
       alertController.addAction(somethingAction)
       alertController.addAction(cancelAction)
       present(alertController, animated: true, completion:{})


    }

already try

let date = myDatePicker.date
            let components = Calendar.current.dateComponents([.hour, .minute, .year, .day, .month], from: date)
            let year = components.year!
            let day = components.day!
            let month = components.month!
            let hour = components.hour!
            let minute = components.minute!

so when the user press OK button it prints:

print("dia: \(day), mes: \(month), año: \(year), hora: \(hour), minuto: \(minute)")

Print shows current day, month, year, hour and minute im expect to get what the user selected from UIDatePicker

Upvotes: 0

Views: 99

Answers (1)

hrmncd
hrmncd

Reputation: 1045

You initialize a datePicker and get the date from it immediately. This is the problem.

If you want to get the date from the datePicker at the time OK button pressed, you must do this in your closure. Move let date = myDatePicker.date line into your closure, Like so:

let somethingAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default) { (somethingAction: UIAlertAction!) in
                       let date = self.myDatePicker.date
                       print("dia: \(day), mes: \(month), año: \(year), hora: \(hour), minuto: \(minute)")
            }

Upvotes: 1

Related Questions