从文本字段上的日期选择器设置当前日期 [英] Set current date from datepicker on textfield

查看:26
本文介绍了从文本字段上的日期选择器设置当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在文本字段上设置日期选择器.为此,这就是我所写的……(在 viewDidLoad 中)

I'm setting a datepicker on a textfield. For that this is what I've written..(in viewDidLoad)

    let datePicker = UIDatePicker()
    datePicker.datePickerMode = UIDatePickerMode.date
    datePicker.addTarget(self, action: #selector(AddDetailsViewController.theDatePickerValueChanged(sender:)), for: .valueChanged)
    dateTimeTextfield.inputView = datePicker

viewDidLoad 之外,我有这样的函数 theDatePickerValueChanged...

And outside viewDidLoad I have the function theDatePickerValueChanged given like so...

@objc func theDatePickerValueChanged(sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .medium
    dateTimeTextfield.text = formatter.string(from: sender.date)
}

但是现在发生的事情是当我点击文本字段时,datePicker 出现了.但是如果我想在文本字段上设置当前日期,那么我必须从 datePicker 上的当前日期向前或向后移动,然后再次返回到当前日期.

But now what happens is when I tap on the textfield, the datePicker comes up. But if I want the current date to be set on the textfield, then I have to move forward or backward from the current date on the datePicker and then again return to that current date.

但我想要的是当 datePicker 出现时,它的当前日期应该直接设置在文本字段上,而我不需要从当前日期前进或后退.我怎样才能做到这一点......?

But what I want is when the datePicker comes up, the current date on it should be directly set on the textfield without me requiring to go forward or backwards from the current date. How can I achieve this...?

推荐答案

您可以实现文本字段委托方法 textFieldShouldBeginEditing: 并且在该委托方法中您需要这样做...

You can implement text field delegate method textFieldShouldBeginEditing: and in that delegate method you need to do like this...

func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {

  if dateTimeTextfield.text!.isEmpty {
    let formatter = DateFormatter()
    formatter.dateStyle = .medium
    formatter.timeStyle = .medium
    dateTimeTextfield.text = formatter.string(from: Date())
  }
  return true
}

不要忘记设置dateTimeTextfield.delegate = self.

这篇关于从文本字段上的日期选择器设置当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆