UIDatePicker设置最小和最大时间

时间:2013-11-08 15:45:55

标签: ios uidatepicker

我只有时间UIDatePicker我需要设置最小值和最大小时的可能性。例如,我需要它在6小时开始并在15小时结束。是否可以使用UIDatePicker执行此操作?

3 个答案:

答案 0 :(得分:0)

请使用:

datePicker.maximumDate = myMaxDate;
datePicker. minimumDate = myMinDate;

myMaxDate和myMinDate是NSDate个对象

答案 1 :(得分:0)

至于我的问题,maximumDateminimumDate的答案并不是我想要的。也许我的解决方案不是那么明确和正确,但它对我来说很有用。 我已使用UIDatePicker更改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”...... etc}。这是自定义分钟选择器的一个示例,您可以为小时等编写相同的东西,选择您自己的最大值和最小值。这对我很好。

答案 2 :(得分:0)

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)将这些日期分配给您的挑选者视图

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)
}

那就是:)