Swift: using UIDatePicker as UITextField inputView not updating

前端 未结 3 1730
-上瘾入骨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条回答
  •  囚心锁ツ
    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.

提交回复
热议问题