我想切换时间洗涤器做15分钟的间隔

请build议我,我想在15分钟的时间间隔。 例如:4点,4点15分,4点30分,4点45分等等。

@IBAction func sliderMoved(sender: UISlider) { let slot = Double(sender.value) let slotDate = self.timeFromSlot(slot) print(timeFormatter.stringFromDate(slotDate!)) } private func timeFromSlot(slot:Double) -> NSDate? { let cal = NSCalendar.currentCalendar() let unit:NSCalendarUnit = [.Year, .Month, .Day, .Hour, .Minute, .Second] let comps = cal.components(unit, fromDate: NSDate()) comps.hour = Int((slot % (24 * 3600)) / 3600) comps.minute = Int(slot % 3600 / 60) comps.second = 0 let startedDate = cal.dateFromComponents(comps)! return startedDate } 

我有sliderMoved起点是8:00 AM和结束点9:00 PM我已经设置滑块最小值28,800和最大值75,600,当我滑动滑块的值是改变与我的timeFromSlot方法和更改的值我得到8:01 8:02 8:03之间..我想要改变的价值8:00 8:15 8:30这样。

对于你的情况,最好使用一些缩放比例的部分。 试试下面的代码。 我相信这很简单。

 import UIKit class ViewController: UIViewController { @IBOutlet weak var slider: UISlider! @IBOutlet weak var label: UILabel! let ticksCount: Float = 13*4 // 15mins intervals count from 8am till 9pm let calendar = NSCalendar.currentCalendar() let todayDate = NSDate() override func viewDidLoad() { super.viewDidLoad() slider.minimumValue = 0 slider.maximumValue = ticksCount } @IBAction func onValueChanged(slider: UISlider) { let minutesFromDayStart = 8 * 60 + Int(slider.value) * 15 // total minutes from day start, assuming we use intervals from 8am let timeSlotDate = dateWithTimeSlotForDate(todayDate, minutesFromDayStart: minutesFromDayStart) showDate(timeSlotDate) } private func showDate(date: NSDate) { let df = NSDateFormatter() df.dateStyle = .MediumStyle df.timeStyle = .MediumStyle label.text = df.stringFromDate(date) } private func dateWithTimeSlotForDate(date: NSDate, minutesFromDayStart: Int) -> NSDate { let dayStart = dayStartDateForDate(date) return calendar.dateByAddingUnit(.Minute, value: minutesFromDayStart, toDate: dayStart, options: NSCalendarOptions(rawValue: 0))! } private func dayStartDateForDate(date: NSDate) -> NSDate { return calendar.startOfDayForDate(date) } } 

应该是这样的

  yourSlider.continuous = false @IBAction func sliderMoved(sender: UISlider) { let slot = Double(sender.value) let slotDate = self.timeFromSlot(slot) print(timeFormatter.stringFromDate(slotDate!)) if (sender.value >= 28800 && sender.value < your next interval 1) { sender.value = 28800 } else if (sender.value >= your next interval 1 && sender.value < your next interval 2) { sender.value = your next interval 1 } else if .... }