Swift: using UIDatePicker as UITextField inputView not updating

前端 未结 3 1731
-上瘾入骨i
-上瘾入骨i 2020-12-14 08:07

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 th

相关标签:
3条回答
  •     let selectedDate = datePicker.date
        print(selectedDate)
        let formatter = DateFormatter()
        formatter.dateFormat = "dd/MM/yyyy"
        let strDate = formatter.string(from: selectedDate)
        self.labelDate.text = strDate
    
    0 讨论(0)
  • 2020-12-14 08:51
    datePicker = UIDatePicker(frame:CGRect(x: 0, y: self.view.frame.size.height-180 , width: self.view.frame.size.width, height: 200))
        self.view.addSubview(datePicker)
        datePicker.datePickerMode = UIDatePickerMode.dateAndTime
        datePicker.isHidden = true
        button.isSelected = false
        datePicker.addTarget(self, action: #selector(self.dateSelected), for: UIControlEvents.valueChanged)
    
     @objc func dateSelected()
    {
        let dateformatter1 = DateFormatter()
        dateformatter1.dateFormat = "ccc, d MMM yyy"
    
        let dateString1 = dateformatter1.string(from: datePicker.date)
        print("Date Selected \(dateString1)")
        labelDate.text = dateString1
    
        let dateformatter2 = DateFormatter()
        dateformatter2.dateFormat = "dd-MM-yyyy"
        let dateString2 = dateformatter2.string(from: datePicker.date)
        print("Date Selected \(dateString2)")
    
    
        let dateformatter3 = DateFormatter()
        dateformatter3.dateFormat = "dd/MM/yyyy"
        let dateString3 = dateformatter3.string(from: datePicker.date)
        print("Date Selected \(dateString3)")
    
        let dateformatter4 = DateFormatter()
        dateformatter4.dateFormat = "dd MMMM yyyy hh:mm a"
        let dateString4 = dateformatter4.string(from: datePicker.date)
        print("Date Selected \(dateString4)")
    
    }
    

    This article on DatePicker and NSDateFormat helped me a lot.

    0 讨论(0)
  • 2020-12-14 09:01

    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)
    }
    
    0 讨论(0)
提交回复
热议问题