【问题标题】:Get selected Day from UIDatePicker alert从 UIDatePicker 警报中获取选定的日期
【发布时间】:2020-03-26 00:04:21
【问题描述】:

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

【问题讨论】:

  • 我无法理解你的问题。你期望的结果是什么,你会得到什么?
  • 感谢@Teo 已经编辑了我的问题

标签: swift uidatepicker


【解决方案1】:

您初始化一个 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)")
            }

【讨论】:

  • 感谢 myDatePicker.addTarget(self, action: #selector(self.cambio(sender:)), for: .valueChanged) 成功了
猜你喜欢
  • 1970-01-01
  • 2016-04-13
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多