iOS Swift Date Picker选择下一个间隔

时间:2018-04-27 23:02:40

标签: ios swift datepicker intervals

我想知道是否有方法选择时间选择器的日期到下一个间隔而不是最近:如果它是1:47,我希望选择器显示2:00和不是1:45 .. UIDatePicker是否有任何属性可以选择下一个Interval?

{{1}}

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

您需要为UIControlEvents .valueChanged添加日期选择器的目标,并从所选日期获取分钟组件。要计算下一个小时的分钟,您可以使用以下公式(x - x % 15 + 15) % 60

import UIKit
class ViewController: UIViewController {
    @IBOutlet weak var datePicker: UIDatePicker!
    override func viewDidLoad() {
        super.viewDidLoad()
        datePicker.addTarget(self, action: #selector(datePickerValueChanged), for: .valueChanged)
    }
    @objc func datePickerValueChanged(datePicker: UIDatePicker) {
        if datePicker.date.minute % 15 != 0 {
            if datePicker.date.minute > 45 {
                datePicker.date += 60*60
            }
            datePicker.date = datePicker.date.nextHourQuarter
        } 
    }
}
extension Int {
    var nextHourQuarter: Int {
        return (self - self % 15 + 15) % 60
    }
}
extension Date {
    var hour: Int { return Calendar.current.component(.hour, from: self) }
    var minute: Int { return Calendar.current.component(.minute, from: self) }
    var nextHourQuarter: Date {
        return  Calendar.current.date(bySettingHour: hour, minute: minute.nextHourQuarter, second: 0, of: self)!
    }
}

Sample

答案 1 :(得分:0)

UIDatePicker类没有该功能。您只能锁定选择器以允许某些值(例如,如果您设置datePicker.minuteInterval = 15,则可用选项将从初始时间开始并以15分钟为单位)。

您可以通过监听值更改通知并手动设置时间(最好使用动画)来自行实现此行为。

答案 2 :(得分:0)

我想我的意思并不清楚。 我已经编写了这个函数,它将选择器时间设置为下一个间隔。 我不知道它是否正确但是有效:

  • 日期8:03 - >选择日期是8:15
  • 日期8:23 - >选择日期是8:30
  • 日期8:38 - >选择日期是8:45
  • 日期8:46 - >选择日期是9:00

viewDidLoad中:

let datePicker = UIDatePicker()
datePicker.datePickerMode = UIDatePickerMode.time
datePicker.minuteInterval = 15
datePicker.date = setDatePickerTime(datePicker: datePicker)

将DatePicker时间设置为下一个15分钟的时间间隔

func setDatePickerTime(datePicker: UIDatePicker) -> Date {
  let calendar = Calendar.current
  let currentHour = calendar.component(.hour, from: Date())
  let currentMinute = calendar.component(.minute, from: Date())

  let dateFormatter = DateFormatter()
  dateFormatter.dateFormat =  "HH:mm"

  var pickerOutHour = ""
  var pickerOutMinute = ""

  if (currentMinute > 45 && currentMinute < 60){
      pickerOutMinute = "00"
      pickerOutHour = String((Int(currentHour) + 1) % 24)
  } else if (currentMinute > -1 && currentMinute < 16){
      pickerOutMinute = "15"
      pickerOutHour = String(currentHour)
  } else if (currentMinute > 15 && currentMinute < 31){
      pickerOutMinute = "30"
      pickerOutHour = String(currentHour)
  } else if (currentMinute > 30 && currentMinute < 46){
      pickerOutMinute = "45"
      pickerOutHour = String(currentHour)
  }

  let pickerOutDate = dateFormatter.date(from: pickerOutHour + ":" + pickerOutMinute)
  return pickerOutDate!
}