在 UIDatePicker 中添加两个小时的间隔

Add two hours intervals in UIDatePicker

我需要为我的 UIDatePicker 添加两个小时的间隔。

第一个间隔应包含从 12:00 到 15:00 的小时数,第二个间隔应包含从 19:00 到 22:00 的小时数。 有什么办法吗?

谢谢!

尝试自己创建时间对象并在 UIPickerView 中显示它们。 https://developer.apple.com/documentation/uikit/uipickerview

正如@Isuru 和@Eli Gooch 所说。我使用 UIPickerView 创建了一个自定义时间对象。我的实现:

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