从 UIDatePicker 警报中获取选定的日期

Get selected Day from UIDatePicker alert

嗨开发者我正在尝试从 UIDatePicker 获取日期和时间 我的 UIDatePicker 处于警报状态

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:{})


    }

已经尝试

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!

所以当用户按下 OK 按钮时,它会打印:

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

打印显示当前日、月、年、小时和分钟 我希望得到用户从 UIDatePicker

中选择的内容

您初始化一个 datePicker 并立即从中获取日期。就是这个问题。

如果你想在按下 OK 按钮时从 datePicker 中获取日期,你必须在你的闭包中这样做。将 let date = myDatePicker.date 行移动到你的闭包中,像这样:

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)")
            }