skip to Main Content

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!

2

Answers


  1. Chosen as BEST ANSWER

    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)"
    }
    

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search