【问题标题】:UIDatePicker with 15m interval but always exact time as return value具有 15m 间隔的 UIDatePicker 但始终将准确时间作为返回值
【发布时间】:2011-11-22 04:11:54
【问题描述】:

我有一个处于时间模式的 UIDatePicker,间隔为 15 分钟。

假设现在是晚上 7:22。日期选择器默认显示的值是四舍五入到下一个更高/更低值的当前时间,在这种情况下,它是晚上 7:15。如果用户与日期选择器交互,则显示的值也是返回的值。但是,如果没有任何用户交互并且我得到了[UIDatePicker date] 的时间,则返回值是确切的当前时间,即 7:22 以坚持示例。

是否有任何方法可以始终获取日期选择器上实际显示的值,而不是当前未取整的时间,即使用户没有明确选择值?

我已经尝试使用 [UIDatePicker setDate:[NSDate date]] 手动设置选择器,但这不会改变行为。

【问题讨论】:

  • 问题是存储在日期选择器中的日期与显示的值不匹配,直到用户更改选择器值。这要求将预先固定的日期输入选择器,否则如果用户没有明确更改显示的值,则不会固定结果。结果是输出值将不是用户所期望的,因为它不是他们所看到的。我可以理解为什么它不会自动调整(简单,以及保留其他时间组件,例如在某些情况下可能希望对用户隐藏的秒数)但是我们如何强制它?
  • @ima747 感谢您的澄清!

标签: objective-c ios xcode uidatepicker


【解决方案1】:

我已经修改了 @ima747 对 Swift 3/4 的回答,并作为 UIDatePicker 的扩展。 picker.clampedDate

extension UIDatePicker {
    /// Returns the date that reflects the displayed date clamped to the `minuteInterval` of the picker.
    /// - note: Adapted from [ima747's](http://stackoverflow.com/users/463183/ima747) answer on [Stack Overflow](http://stackoverflow.com/questions/7504060/uidatepicker-with-15m-interval-but-always-exact-time-as-return-value/42263214#42263214})
    public var clampedDate: Date {
        let referenceTimeInterval = self.date.timeIntervalSinceReferenceDate
        let remainingSeconds = referenceTimeInterval.truncatingRemainder(dividingBy: TimeInterval(minuteInterval*60))
        let timeRoundedToInterval = referenceTimeInterval - remainingSeconds
        return Date(timeIntervalSinceReferenceDate: timeRoundedToInterval)
    }
}

【讨论】:

  • 你能解释一下吗?
【解决方案2】:

这不是一个完美的解决方案,但它对我有用。我从另一篇文章中获取了它并对其进行了修改以接受不同的值。

- (NSDate*)clampDate:(NSDate *)dt toMinutes:(int)minutes {
    int referenceTimeInterval = (int)[dt timeIntervalSinceReferenceDate];
    int remainingSeconds = referenceTimeInterval % (minutes*60);
    int timeRoundedTo5Minutes = referenceTimeInterval - remainingSeconds; 
    if(remainingSeconds>((minutes*60)/2)) {/// round up
        timeRoundedTo5Minutes = referenceTimeInterval +((minutes*60)-remainingSeconds);            
    }
    return [NSDate dateWithTimeIntervalSinceReferenceDate:(NSTimeInterval)timeRoundedTo5Minutes];
}

向它提供一个输入日期和一个分钟值(在此线程的情况下取自 UIDatePicker.minuteInterval),它将返回一个固定在该时间间隔内的时间,您可以将其提供给选择器。

【讨论】:

    【解决方案3】:

    @ima747 是正确的,如果我更改了日期选择器的默认值,那么它工作正常,如果我在没有 onChange 的情况下从选择器控件读取日期,那么它返回错误的日期值。
    但我已经检查过了,日期选择器控件已设置默认日期(当前日期,可能是使用最近的时间毫秒)如果我将其设置为自定义日期并将时间设置为任何日期和 1:00:AM 所以现在我的时间选择器总是以 1:00:AM 打开而不是当前时间

    【讨论】:

      猜你喜欢
      • 2014-11-16
      • 2012-07-19
      • 2011-01-23
      • 2013-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-21
      相关资源
      最近更新 更多