14

I successfully make datePicker view over my UITextField in Swift. But I need to time picking in the format of HH:MM:SS. I have no idea about it. I need to apply picked time in time UITextField. so, How to make Time Picker in Swift? please refer below image. swift 2.2 , 2.0 answers also okay. Thanks lot friends!

enter image description here

0

3 Answers 3

21

Updated for Swift 3:

If you want to show the time picker, use the lines of code for Swift 3 below:

Variable Declarations:

let timePicker = UIDatePicker()

Method Definition:

func openTimePicker()  {
    timePicker.datePickerMode = UIDatePickerMode.time
    timePicker.frame = CGRect(x: 0.0, y: (self.view.frame.height/2 + 60), width: self.view.frame.width, height: 150.0)
    timePicker.backgroundColor = UIColor.white
    self.view.addSubview(timePicker)
    timePicker.addTarget(self, action: #selector(yourViewControllerName.startTimeDiveChanged), for: UIControlEvents.valueChanged)
}

func startTimeDiveChanged(sender: UIDatePicker) {
    let formatter = DateFormatter()
    formatter.timeStyle = .short
    youtTextFieldName.text = formatter.string(from: sender.date)
    timePicker.removeFromSuperview() // if you want to remove time picker
}
1
  • problem with this is.... when you select hours and you had a sec of pause it will auto close it. anyone is trying to do this solution might want to add a flagging to the code of check if finish editting or make another viewcontroller using this method. code work. user experience need improvement. voted +1 Apr 9, 2018 at 3:10
14

Set the datePickerMode to time

Swift 3

self.datePicker.datePickerMode = .time

Swift 2.3 or lower

self.datePicker.datePickerMode = .Time

Note: This will allow you to only select Hours and Minutes, if you want to select Seconds also you need to go for custom time picker.

0
-1

Added for Swift 5+

for timer (it doesn't show seconds part. )

@IBOutlet weak var timerPicker: UIDatePicker!
...
 self.timerPicker.datePickerMode = .countDownTimer
 print("countdown duration",  String(timerPicker.countDownDuration))

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.