我想将占位符日期显示为当前日期

时间:2019-06-01 06:59:55

标签: ios swift uitextfield nsdateformatter

我正在使用日期选择器,默认情况下,当我打开它时将是当前日期。但是现在我想将占位符日期也显示为当前日期。

private func showDatePicker(_ sender: UITextField){
    datePickerView.datePickerMode = UIDatePicker.Mode.date
    sender.inputView = datePickerView
    let toolbar = UIToolbar();
    toolbar.sizeToFit()
    let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(donedatePicker));
    let spaceButton = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
    let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelDatePicker));
    toolbar.setItems([doneButton,spaceButton,cancelButton], animated: false) sender.inputAccessoryView = toolbar sender.inputView = datePickerView;
}

@objc func donedatePicker(){
    let formatter = DateFormatter()
    formatter.dateFormat = "dd/MM/yy"
    if (selectedDateField == 1){
        datePickerView.minimumDate = NSDate() as Date
        sOdateTxt.text = formatter.string(from:datePickerView.date)
        sOdateTxt.placeholder=formatter.string(from:datePickerView.date)
    } else if (selectedDateField == 2){
        datePickerView.minimumDate = NSDate() as Date
        sRdateTxt.text = formatter.string(from:datePickerView.date)
    } else if (selectedDateField == 3){
        datePickerView.minimumDate = NSDate() as Date
        sRecordedTxt.text = formatter.string(from:datePickerView.date)
    }
    self.view.endEditing(true)
}
@objc func cancelDatePicker(){
    self.view.endEditing(true)
}

占位符日期应为当前日期

2 个答案:

答案 0 :(得分:0)

使用viewDidLoad,在Date()方法中使用当前日期为文本字段设置占位符

override func viewDidLoad() {
    super.viewDidLoad()
    sOdateTxt.placeholder = formatter.string(from: Date())
    sRdateTxt.text = formatter.string(from: Date())
    sRecordedTxt.text = formatter.string(from: Date())
}

您不需要使用NSDate() as Date来获取当前日期。您可以使用Date()

答案 1 :(得分:0)

extension Date {
func toString(format:String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = format
    return dateFormatter.string(from: self)
}

}

用法

yourtextfield.placeholder = Date()。toString(格式:“ dd-MM-yyyy”)