UIDatePickerModeTime限制时间选择或设置时间范围

时间:2016-02-20 04:26:05

标签: ios objective-c uidatepicker

我已经编写了以下代码来为pickerView选择时间。这是完美的工作现在我想知道如何设置上午9点到下午5点之间的时间范围。请有人帮我实现在上午9点到下午5点之间限制时间选择的要求。

@interface CleaningDetails ()<UITextFieldDelegate>
{
IBOutlet TextFieldValidator *cleanTime;
UIDatePicker *time;
}
@implementation
       time = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
        time.datePickerMode = UIDatePickerModeTime;
        time.minuteInterval = 30;
        // set change the inputView (default is keyboard) to UIPickerView
        [self.cleanTime setInputView:time];
        // add a toolbar with Cancel & Done button
        UIToolbar *toolBar1 = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
        toolBar1.barStyle = UIBarStyleBlackOpaque;
        UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(showSelectedTime)];
        UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelTouched:)];
        // the middle button is to make the Done button align to right
        [toolBar1 setItems:[NSArray arrayWithObjects:cancelButton, [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil], doneButton, nil]];
        [self.cleanTime setInputAccessoryView:toolBar1];

我对这个编程和目标非常陌生 - 特别是任何人都可以向我建议一些来源或任何想法来完成这项要求。

2 个答案:

答案 0 :(得分:2)

UIDatePicker仅支持最短和最长日期,而不是时间。但是你将使用时间间隔设置时间,使用下面的代码并设置你的时间,

NSDate *minDate = [NSDate new];
// One hour from now
NSDate *maxDate = [[NSDate alloc] initWithTimeIntervalSinceNow:60*60];

UIDatePicker *picker = [UIDatePicker new];
[picker setDatePickerMode:UIDatePickerModeDateAndTime];
[picker setMinimumDate:minDate];
[picker setMaximumDate:maxDate];

希望它有用

答案 1 :(得分:0)

试试这段代码,

require

您将获得返回时间,然后将UTC时间转换为当地时间,

希望它有所帮助。