How to Set Countdowntimer Mode in Datepicker on Swiftui

How can I set countDownTimer mode in DatePicker on SwiftUI?

The only way to get the countdown behavior right now is by wrapping UIDatePicker in a custom view.

Here is a simplified version of Ailton Vieira Pinto Filho's code using countDownDuration.

import SwiftUI

struct DurationPicker: UIViewRepresentable {
@Binding var duration: TimeInterval

func makeUIView(context: Context) -> UIDatePicker {
let datePicker = UIDatePicker()
datePicker.datePickerMode = .countDownTimer
datePicker.addTarget(context.coordinator, action: #selector(Coordinator.updateDuration), for: .valueChanged)
return datePicker
}

func updateUIView(_ datePicker: UIDatePicker, context: Context) {
datePicker.countDownDuration = duration
}

func makeCoordinator() -> Coordinator {
Coordinator(self)
}

class Coordinator: NSObject {
let parent: DurationPicker

init(_ parent: DurationPicker) {
self.parent = parent
}

@objc func updateDuration(datePicker: UIDatePicker) {
parent.duration = datePicker.countDownDuration
}
}
}

UIDatePicker count Down timer mode doesn't return the correct time in Xcode 10.3

Ok problem solved, maybe it's a bug of XCode.

The problem occurs when you build the datepicker from storyboard and set it's mode paramether to Count Down Timer.
To solve this problem, simply don't set the mode of the datepicker on count down timer from the storyboard but you need to set the mode programmatically with

timepicker.datePickerMode = .countDownTimer

Doing this, the problem is solved

SwiftUI: DatePicker is it possible to display date/time in other timezone then current?

It is possible to do with SwiftUI .environment modifier as in below example

DatePicker("Due Date", selection: $selected,
displayedComponents: [.date, .hourAndMinute]
)
.environment(\.timeZone, TimeZone(secondsFromGMT: 5*60*60)!)

How to change UIDatePicker to a specific time (in code)

You've to change the time, you can do it using NSDateComponents and set the modified date to your DatePicker

var calendar:NSCalendar = NSCalendar.currentCalendar()
let components = calendar.components(NSCalendarUnit.HourCalendarUnit | NSCalendarUnit.MinuteCalendarUnit, fromDate: NSDate())
components.hour = 5
components.minute = 50
datePicker.setDate(calendar.dateFromComponents(components)!, animated: true)


Related Topics



Leave a reply



Submit