Date/Time Picker in Swift 4

11,364

You want minutes and seconds picker. So, default UIDatePicker does not provide this functionality. So, I have make custom picker using UIPickerView.

1) First, write this code in viewDidLoad() method.

    let timePicker: UIPickerView = UIPickerView()
    //assign delegate and datasoursce to its view controller
    timePicker.delegate = self
    timePicker.dataSource = self

    // setting properties of the pickerView
    timePicker.frame = CGRect(x: 0, y: 50, width: self.view.frame.width, height: 200)
    timePicker.backgroundColor = .white

    // add pickerView to the view
    self.view.addSubview(timePicker)

2) Second, make extension of your viewcontroller and give them UIPickerViewDelegate and UIPickerViewDataSource as I have done below.

extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource{

    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 2
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return 60
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return String(format: "%02d", row)
    }

    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        if component == 0{
            let minute = row
            print("minute: \(minute)")
        }else{
            let second = row
            print("second: \(second)")
        }
    }
}

Hope this will help you.

Share:
11,364
Thomas
Author by

Thomas

Updated on August 03, 2022

Comments

  • Thomas
    Thomas over 1 year

    How would I make a Time/Date Picker that allows a selection of minutes and seconds and set that as a countdown time (I only need to know how to make the Time/Date Picker). I've found many tutorials but they are made in the Main.storyboard. I want to add it to my GameScene.swift (file type is Cocoa Touch Class). I am working with Swift 4 in Xcode 9.3 in a Game type application.

    Thanks in advance!

    • Malik
      Malik about 6 years
      You can make one yourself using UIPickerView