2015-09-11 49 views
1

我已經設置了一個日期選擇器作爲文本框的輸入視圖。日期選擇器的最小日期和間隔分鐘爲15.現在它給出更改旋轉值更改代表的適當日期。但是,如果我不旋轉選取器並按默認第一次選擇按鈕完成按鈕,它只給出當前日期。我希望它能給我選擇器中默認顯示的日期。這裏是代碼:ios swift datepicker完成按鈕,錯誤的日期間隔

class ViewController: UIViewController { 

    @IBOutlet weak var timeField: UITextField! 

    var datePicker:UIDatePicker! 

    override func viewDidLoad() { 
     super.viewDidLoad() 

    } 

    @IBAction func CallPicker(sender: UITextField) { 

     let datePickerView:UIDatePicker = UIDatePicker() 
     datePickerView.datePickerMode = UIDatePickerMode.DateAndTime 
     datePickerView.minuteInterval = 15 
     datePickerView.minimumDate = NSDate() 
     datePicker = datePickerView 

     let toolBar = UIToolbar() 
     toolBar.sizeToFit() 
     let spaceButton = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil) 
     let doneButton = UIBarButtonItem(title: "Done", style: .Plain, target: self, action: "doneTapped") 
     toolBar.setItems([spaceButton, doneButton], animated: false) 
     toolBar.userInteractionEnabled = true 

     sender.inputView = datePickerView 
     sender.inputAccessoryView = toolBar 
     datePickerView.addTarget(self, action: Selector("datePickerValueChanged:"), forControlEvents: UIControlEvents.ValueChanged) 
    } 

    func doneTapped() { 
     let dateFormatter = NSDateFormatter() 
     dateFormatter.dateStyle = .MediumStyle 
     dateFormatter.timeStyle = .MediumStyle 
     timeField.text = dateFormatter.stringFromDate(datePicker.date) 
     timeField.resignFirstResponder() 
    } 

    func datePickerValueChanged(sender: UIDatePicker) { 
     let dateFormatter = NSDateFormatter() 
     dateFormatter.dateStyle = .MediumStyle 
     dateFormatter.timeStyle = .MediumStyle 
     timeField.text = dateFormatter.stringFromDate(sender.date) 
    } 

} 

場景:假設它現在是8:42。日期選擇器將顯示8:30作爲第一個輸入,但是當我點擊完成按鈕時,它只會給當前時間8:42。不過,如果我旋轉並回到第一次輸入,它會很好。

+0

你摸不着頭腦嘗試使用下面的代碼? –

回答

-1

你只需要將此datePicker的date屬性從當前日期設置爲custom,然後它就可以工作。

+0

它不起作用。 – Azam

0

時的日期選擇

let userDateFormate = NSDateFormatter() 
    userDateFormate.dateFormat = "MMMM dd, yyyy" 
    let dateString = userDateFormate.stringFromDate(date) 

    dateFormate.dateFormat = "MMMM dd, yyyy" 
    dateFormate.timeZone = NSTimeZone.init(forSecondsFromGMT: 0) 
    let dateValue = dateFormate.dateFromString(dateString)