I've got a UIDatePicker
with the time only and I need a possibility to set the minimum and the maximum hour is showed. For example, I need it to start at 6 hours and finish at 15 hrs. Is it possible to perform this with UIDatePicker
?
问问题
5924 次
3 回答
1
1) 使用此函数检索最小和最大日期
func getTimeIntervalForDate()->(min : Date, max : Date){
let calendar = Calendar.current
var minDateComponent = calendar.dateComponents([.hour], from: Date())
minDateComponent.hour = 09 // Start time
let formatter = DateFormatter()
formatter.dateFormat = "h:mma"
let minDate = calendar.date(from: minDateComponent)
print(" min date : \(formatter.string(from: minDate!))")
var maxDateComponent = calendar.dateComponents([.hour], from: date)
maxDateComponent.hour = 17 //EndTime
let maxDate = calendar.date(from: maxDateComponent)
print(" max date : \(formatter.string(from: maxDate!))")
return (minDate!,maxDate!)
}
2)将这些日期分配给您的pickerview
func createPickerView(textField : UITextField, pickerView : UIDatePicker){
pickerView.datePickerMode = .time
textField.delegate = self
textField.inputView = pickerView
let dates = getTimeIntervalForDate()
pickerView.minimumDate = dates.min
pickerView.maximumDate = dates.max
pickerView.minuteInterval = 30
pickerView.addTarget(self, action: #selector(self.datePickerValueChanged(_:)), for: UIControlEvents.valueChanged)
}
而已 :)
于 2017-05-28T18:41:19.853 回答
0
只需使用这个:
datePicker.maximumDate = myMaxDate;
datePicker. minimumDate = myMinDate;
其中 myMaxDate 和 myMinDate 是NSDate
对象
于 2013-11-08T15:49:31.757 回答
0
至于我的问题,答案maximumDate
不是minimumDate
我想要的。也许我的解决方案不是那么清晰和正确,但对我来说效果很好。我已经改变了UIDatePicker
with UIPickerView
,为它写了一个单独的代表:
@interface CHMinutesPickerDelegate () <UIPickerViewDelegate, UIPickerViewDataSource>
@property (nonatomic, strong) NSArray *minutesArray;
@end
@implementation CHMinutesPickerDelegate
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component {
return [self.minutesArray count];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
return 1;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
return [self.minutesArray objectAtIndex: row];
}
- (NSArray *)minutesArray {
if (!_minutesArray) {
NSMutableArray *temporaryMinutesArray = [NSMutableArray array];
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 2; j++) {
[temporaryMinutesArray addObject: [NSString stringWithFormat: @"%i%i", i, j * 5]];
}
}
_minutesArray = temporaryMinutesArray;
}
return _minutesArray;
}
返回数组:{ “ minutesArray
05”、“10”...等}。这是自定义分钟选择器的示例,您可以为小时等编写相同的内容,选择您自己的最大值和最小值。这对我来说很好。
于 2013-11-08T18:31:49.703 回答