Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

ios - Cannot convert string to date for datePicker

I try to get string from textfield, then convert it to date and put this value in datepicker. But for some reason it fails everytime and I get: "There is issue in dateformatter. Not able to convert string to Date".

I don't understand what I'm doing wrong and how I get this works.

My code:

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var DOBTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    DOBTextField.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed), textFieldText: DOBTextField.text)
}

@objc func doneButtonPressed() {
    if let  datePicker = self.DOBTextField.inputView as? UIDatePicker {
        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .none
        self.DOBTextField.text = dateFormatter.string(from: datePicker.date)
    }
    self.DOBTextField.resignFirstResponder()
 }
}


 extension UITextField {

   func addInputViewDatePicker(target: Any, selector: Selector , textFieldText: String?) {


    let screenWidth = UIScreen.main.bounds.width

    let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))
    datePicker.datePickerMode = .date
    self.inputView = datePicker

    let dateFormatter = DateFormatter()
    dateFormatter.dateStyle = .long
    dateFormatter.timeStyle = .none

    if textFieldText != nil {
        if let date = dateFormatter.date(from: textFieldText!) {
            datePicker.date = date
        } else {
        print("There is issue in dateformatter. Not able to convert string to Date ")
        }
      }
     else {
      datePicker.date = Date()
    }


    //Add Tool Bar as input AccessoryView
    let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
    let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
    let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
    let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
    toolBar.setItems([cancelBarButton, flexibleSpace, doneBarButton], animated: false)

    self.inputAccessoryView = toolBar
 }

   @objc func cancelPressed() {
     self.resignFirstResponder()
   }
}

I don't understand what I'm doing wrong and why this code doesn't work. May be someone can help me resolve this issue?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As I see when you call addInputViewDatePicker on viewDidLoad, the value of textFieldText is "" that's why you see your print from start

you can try use this code (but, I guess, you can optimize it):

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var DOBTextField: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()

        prepareDOBTextField()

        DOBTextField.addInputViewDatePicker(target: self, selector: #selector(doneButtonPressed), textFieldText: DOBTextField.text)
    }

    @objc func doneButtonPressed() {
        if let  datePicker = self.DOBTextField.inputView as? UIDatePicker {
            let dateFormatter = DateFormatter()
            dateFormatter.dateStyle = .long
            dateFormatter.timeStyle = .none
            self.DOBTextField.text = dateFormatter.string(from: datePicker.date)
        }
        self.DOBTextField.resignFirstResponder()
    }

    func prepareDOBTextField() {
        let date = Date()
        let formatter = DateFormatter()
        formatter.dateStyle = .long
        formatter.timeStyle = .none
        let result = formatter.string(from: date)

        self.DOBTextField.text = result
    }
}


extension UITextField {

    func addInputViewDatePicker(target: Any, selector: Selector , textFieldText: String?) {


        let screenWidth = UIScreen.main.bounds.width

        let datePicker = UIDatePicker(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 216))
        datePicker.datePickerMode = .date
        self.inputView = datePicker

        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .long
        dateFormatter.timeStyle = .none

        if textFieldText != nil && textFieldText != "" {
              if let date = dateFormatter.date(from: textFieldText!) {
                  datePicker.date = date
              } else {
                  print("There is issue in dateformatter. Not able to convert string to Date ")
              }
          }
          else {
              datePicker.date = Date()
          }

        //Add Tool Bar as input AccessoryView
        let toolBar = UIToolbar(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 44))
        let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
        let cancelBarButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(cancelPressed))
        let doneBarButton = UIBarButtonItem(title: "Done", style: .plain, target: target, action: selector)
        toolBar.setItems([cancelBarButton, flexibleSpace, doneBarButton], animated: false)

        self.inputAccessoryView = toolBar
    }

    @objc func cancelPressed() {
        self.resignFirstResponder()
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...