【问题标题】:How do I convert Date into DateComponents in SwiftUI?如何在 SwiftUI 中将 Date 转换为 DateComponents?
【发布时间】:2020-06-18 01:56:04
【问题描述】:

我想在用户从 DatePicker 中选择时设置每日通知,但我不知道如何将选定的小时和分钟转换为 DateComponents 以匹配 UNCalendarNotificationTrigger。

这是我的日期选择器:

DatePicker("Choose time of notif", selection: $notifTime, displayedComponents: .hourAndMinute)

这是我的通知触发器:

var dateComponents = DateComponents()
dateComponents = notifTime
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

【问题讨论】:

    标签: swift datepicker notifications uikit swiftui


    【解决方案1】:

    您只需要使用Calendar API 从date 属性中获取dateComponents,这需要重复。因此,在这种情况下,小时和分钟每天都会重复,因此您可以这样做:

    var notifTime: Date
    let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: notifTime)
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 2012-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 2019-09-05
      相关资源
      最近更新 更多