UIDatePicker 15 Minute Increments Swift
Set shedulePicker.minuteInterval = 15
I found the answer here:
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIDatePicker_Class/#//apple_ref/occ/instp/UIDatePicker/minuteInterval
It's always good to take a look at documentation :)
UIDatePicker with 5 min interval get date on appear with interval
you could check the date and round it to your needs like this:
override func viewDidLoad() {
super.viewDidLoad()
let calendar = Calendar.current
var dateComponents = calendar.dateComponents([.month, .day, .year, .hour, .minute], from: datePicker.date)
guard var hour = dateComponents.hour, var minute = dateComponents.minute else {
print("something went wrong")
return
}
let intervalRemainder = minute % datePicker.minuteInterval
if intervalRemainder > 0 {
// need to correct the date
minute += datePicker.minuteInterval - intervalRemainder
if minute >= 60 {
hour += 1
minute -= 60
}
// update datecomponents
dateComponents.hour = hour
dateComponents.minute = minute
// get the corrected date
guard let roundedDate = calendar.date(from: dateComponents) else {
print("something went wrong")
return
}
// update the datepicker
datePicker.date = roundedDate
}
}
feel free to ask if anything is unclear!
Add two hours intervals in UIDatePicker
Like @Isuru & @Eli Gooch said. I have created a custom time object using UIPickerView. My implementation:
//Declaration of variables
let picker = UIPickerView()
let hoursRange = Array(arrayLiteral: 12, 13, 14, 19, 20, 21, 22)
let minRange = Array(arrayLiteral: 00, 30)
var hourSelected: String = "00"
var minSelected: String = "00"
//Added UIPickerViewDataSource and UIPickerViewDelegate in my class
picker.dataSource = self
picker.delegate = self
//Set number of components
func numberOfComponents(in: UIPickerView) -> Int {
return 2
}
//Set value into every component element
func pickerView(_ pickerView: UIPickerView,
numberOfRowsInComponent component: Int) -> Int {
//Hour component
if component == 0 {
return hoursRange.count
}
//Minutes component
return minRange.count
}
//Delegate
func pickerView(_ pickerView: UIPickerView,
titleForRow row: Int,
forComponent component: Int) -> String? {
switch component {
case 0:
//Return hours value
return "\(hoursRange[row])"
case 1:
//Return minutes value
return "\(minRange[row])"
default:
return nil
}
}
//To get value
func pickerView(_ pickerView: UIPickerView,
didSelectRow row: Int,
inComponent component: Int) {
if component == 0 {
hourSelected = "\(hoursRange[row])"
} else {
if minRange[row] != 0 {
minSelected = "\(minRange[row])"
} else {
minSelected = "00"
}
}
hourTextField?.text = "\(hourSelected) : \(minSelected)"
}
How to get hours and minutes from UIDatePicker
UIDatePicker
just give you the selected Date
, if you need the date component based on current calendar, check out the Calendar
and DateComponent
documendation for details.
let now = Date() // your date
let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: now)
dateComponents.hour
dateComponents.minute
If you need hours
and minutes
for time distance, you need the calculate it manually with your prefer base date.
DatePicker using Time-Interval in SwiftUI
I don't believe there is a modifier for this. However it's possible to "do it yourself" by using UIViewRepresentable to wrap a UIDatePicker:
The basic structure for this code is based on the Interfacing with UIKit tutorial.
struct MyDatePicker: UIViewRepresentable {
@Binding var selection: Date
let minuteInterval: Int
let displayedComponents: DatePickerComponents
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
func makeUIView(context: UIViewRepresentableContext<MyDatePicker>) -> UIDatePicker {
let picker = UIDatePicker()
// listen to changes coming from the date picker, and use them to update the state variable
picker.addTarget(context.coordinator, action: #selector(Coordinator.dateChanged), for: .valueChanged)
return picker
}
func updateUIView(_ picker: UIDatePicker, context: UIViewRepresentableContext<MyDatePicker>) {
picker.minuteInterval = minuteInterval
picker.date = selection
switch displayedComponents {
case .hourAndMinute:
picker.datePickerMode = .time
case .date:
picker.datePickerMode = .date
case [.hourAndMinute, .date]:
picker.datePickerMode = .dateAndTime
default:
break
}
}
class Coordinator {
let datePicker: MyDatePicker
init(_ datePicker: MyDatePicker) {
self.datePicker = datePicker
}
@objc func dateChanged(_ sender: UIDatePicker) {
datePicker.selection = sender.date
}
}
}
struct DatePickerDemo: View {
@State var wakeUp: Date = Date()
@State var minterval: Int = 1
var body: some View {
VStack {
Stepper(value: $minterval) {
Text("Minute interval: \(minterval)")
}
MyDatePicker(selection: $wakeUp, minuteInterval: minterval, displayedComponents: .hourAndMinute)
Text("\(wakeUp)")
}
}
}
struct DatePickerDemo_Previews: PreviewProvider {
static var previews: some View {
DatePickerDemo()
}
}
How to limit date selection on UIDatePicker
Configure your picker with a minuteInterval
datePicker.minuteInterval = 5
will make the picker increment in 5 minute intervals.
You can set the minute interval to whatever interval you need, but the number must evenly divide into 60
SwiftUI - .hourAndMinute showing only 00 and 30' minutes
The comment posted is wrong. You can of course do this with a one line piece of code:
UIDatePicker.appearance().minuteInterval = 30
The issue is that now all of your time pickers throughout your entire app will be in 30 minute increments. To alleviate this, you use .onAppear and .onDisappear as follows:
.onAppear {
UIDatePicker.appearance().minuteInterval = 30
}
.onDisappear {
UIDatePicker.appearance().minuteInterval = 1
}
Now, when your view appears the picker will be set to 30 minute increments. When the view disappears, it will be set back to the default of 1 minute increments.
Now you can easily control what time increment is displayed on a per view basis.
Related Topics
Nscalendar in Swift - Init Can Return Nil, But Isn't Optional
Localizing The Reading of Emoji on iOS 10.0 or Higher
Using Multiple Hosting Controllers in Swiftui on Watchos
Table View Cells Changing Colors When Scrolling Swift
How to Hide The Status Bar Programmatically in iOS 8
Dependency Injection in View Controller
How to Detect If The User Was Deleted from Firebase Auth
Navigation Link in Bar Items Goes Back to Top of Navigationview
Struct Memberwise Initialization - Omitting Values for Properties That Have Defaults
Convert/Wrap Swift Struct as Nsvalue for Caanimation Purposes
Why Is The Leading Swipe Action Also Duplicated as a Trailing Action
Detect When a Custom Cell Is Selected from Within The Cell Itself
How to Use Swipe to Dismiss While Presenting a Fullscreen Modal in iOS 13
Apple Turicreate Always Return The Same Label