Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

datepicker - Swift: using UIDatePicker as UITextField inputView not updating

I have a textfield and when it is selected a datepicker pops up instead of a keyboard, but it only updates with todays date the first time. The user changes the date, but the textfield does not continue to update. What is the problem?

This is how I call the Datepicker and control the date being inputted into my textfield:

 @IBAction func dp(sender: UITextField) {
    var DatePickerView  : UIDatePicker = UIDatePicker()
    DatePickerView.datePickerMode = UIDatePickerMode.Date
    textfieldjobdate.inputView = DatePickerView
    DatePickerView.addTarget(self, action: Selector("handleDatePicker"), forControlEvents: UIControlEvents.ValueChanged)    
}

func handleDatePicker() {
    var DatePickerView  : UIDatePicker = UIDatePicker()
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd MMM yyyy"
    textfieldjobdate.text = dateFormatter.stringFromDate(DatePickerView.date)
}
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Your handleDatePicker method is instantiating a new DatePicker each time it's called. You need to add a parameter to the function to pass in the sender (the DatePicker created in func dp)

@IBAction func dp(_ sender: UITextField) {
    let datePickerView = UIDatePicker()
    datePickerView.datePickerMode = .date
    sender.inputView = datePickerView
    datePickerView.addTarget(self, action: #selector(handleDatePicker(sender:)), for: .valueChanged)
}

@objc func handleDatePicker(sender: UIDatePicker) {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MMM yyyy"
    textfieldjobdate.text = dateFormatter.string(from: sender.date)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...