Alfonso Tesone
Alfonso Tesone

Reputation: 138

Add two hours intervals in UIDatePicker

I need to add two hours intervals to my UIDatePicker.

The first interval should contain the hours from 12:00 to 15:00 and the second one from 19:00 to 22:00. Is there any way to do this?

Thank you!

Upvotes: 0

Views: 126

Answers (2)

Alfonso Tesone
Alfonso Tesone

Reputation: 138

Like @Isuru & @Eli Gooch said. I have created a custom time object using UIPickerView. My implementation:

//Declaration of variables
let picker          = UIPickerView()

let hoursRange      = Array(arrayLiteral: 12, 13, 14, 19, 20, 21, 22)
let minRange        = Array(arrayLiteral: 00, 30)

var hourSelected:  String     = "00"
var minSelected:   String     = "00"

 
//Added UIPickerViewDataSource and UIPickerViewDelegate in my class
picker.dataSource    = self
picker.delegate      = self

//Set number of components
func numberOfComponents(in: UIPickerView) -> Int {
    return 2
}
    
//Set value into every component element
func pickerView(_ pickerView: UIPickerView,
                  numberOfRowsInComponent component: Int) -> Int {
   
                //Hour component
                if component == 0 {
                     return hoursRange.count
                }
    
                //Minutes component
               return minRange.count
    
 }

//Delegate
func pickerView(_ pickerView: UIPickerView, 
                  titleForRow row: Int, 
                  forComponent component: Int) -> String? {

        switch component {
            case 0:
                //Return hours value
                return "\(hoursRange[row])"

            case 1:
                //Return minutes value
                return "\(minRange[row])"

            default:
                return nil
        }
}

//To get value
func pickerView(_ pickerView: UIPickerView, 
                  didSelectRow row: Int, 
                  inComponent component: Int) {
    
  
    if component == 0 {
        hourSelected = "\(hoursRange[row])"
    } else {
        
        if minRange[row] != 0 {
           minSelected = "\(minRange[row])"
        } else {
           minSelected = "00"
        }
        
    }
               
    hourTextField?.text     = "\(hourSelected) : \(minSelected)"
}

Upvotes: 1

Eli Gooch
Eli Gooch

Reputation: 110

Try creating the time objects yourself and showing them in a UIPickerView. https://developer.apple.com/documentation/uikit/uipickerview

Upvotes: 0

Related Questions