分享
三行代码  ›  专栏  ›  技术社区  ›  José Raúl Toledano R

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

  •  0
  • José Raúl Toledano R  · 技术社区  · 3 天前

    嗨,开发人员,我正试图从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!
    

    所以当用户按下 按钮打印:

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

    打印显示当前日期、月份、年份、小时和分钟

    1 回复  |  直到 3 天前
        1
  •  1
  •   Teo    3 天前

    初始化日期选择器并立即从中获取日期。这就是问题所在。

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