从UIDatePicker警报中获取所选日期

问题描述 投票:0回答:1

您好,开发人员正在尝试从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中选择的内容

swift uidatepicker
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.