Search code examples
swiftuidatepicker

How to set a specific default time for a date picker in Swift


Is there any way to set a date picker to display a specific time on load? I have four date picker instances initiated from four text fields for Start Time, Finish Time, Start Date and Finish Date using the squimer/datePickerDialog subclass from GitHub that pops up in a UIAlertView.

In my app a default start time would be 7:00 AM and a default finish time would be 5:00 PM and let the user adjust around those times.

All I can see is that you can set the datePicker.defaultDate to currentDate, minimumDate or maximumDate and only once. Is it possible set the defaultDate to hardcoded strings of sTime = "07:00" and fTime = "17:00" in my calls from the ViewController?

Any help would be appreciated.

EDIT: This is how I am calling the subclass from my viewController

@IBAction func setFT(sender: UITextField) {
    resignKeyboardCompletely(sender)
    DatePickerDialog().show("Pick a Finish Time", doneButtonTitle: "Done", cancelButtonTitle: "Cancel", datePickerMode: .Time) {
        (timeFinish) -> Void in
        self.dateFormatter.dateFormat = "HH:mm"
        let finTime = self.dateFormatter.stringFromDate(timeFinish)
        self.finishTime.text = finTime
    }
    defaults.setObject(finishTime.text, forKey: "finishTime")
    print(finishTime.text)
}

Note that throughout this I am also trying to maintain persistence through NSUser Defaults.


Solution

  • Are you looking for setting the time through a string. If that''s the case you can use a date formatter like this.

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat =  "HH:mm"
    
    let date = dateFormatter.dateFromString("17:00")
    
    datePicker.date = date
    

    Adding an init to the Picker class

    init(time:String) {
        super.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.size.width, UIScreen.mainScreen().bounds.size.height))
    
        setupView()
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat =  "HH:mm"
    
        if let date = dateFormatter.dateFromString("17:00") {
            datePicker.date = date
        }
    }