在Xcode上使用NSDatePickerView分别使用日期和时间

时间:2016-03-28 03:50:19

标签: objective-c xcode nsdate nsdatecomponentsformatter

我有一部分应用程序可以设置约会的日期和时间。为此,我有两个NSDatePickerView。第一个我设置为NSDatePickerModeDate,而另一个设置为NSDatePickerModeTime。但实际上它们应该引用NSDate条目中的同一个NSMutableDictionary对象。我知道NSDatePickerModeDateTime,但我需要分开挑选日期和时间。

我知道如何设置NSDatePickerView以显示和隐藏事件控件等等,但在事件控件UIControlEventValueChanged触发NSDatePickerView时,我感到很困惑如何为此更改代码,以及如何初始化选择器(datePicker.date = today, timePicker.date = "9:00 AM")

@interface MyViewController () {
    NSMutableDictionary *data;
}

@end

@implementation MyViewController

@synthesize datePicker, timePicker;

- (void) viewDidLoad {
    [super viewDidLoad];
    data = [[NSMutableDictionary alloc] init];
    [data setObject:[NSDate date] forKey:@"date"];

    datePicker.datePickerMode = UIDatePickerModeDate;
    timePicker.datePickerMode = UIDatePickerModeTime;

    [datePicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged];
    [timePicker addTarget:self action:@selector(changeTime:) forControlEvents:UIControlEventValueChanged];

    datePicker.date = data[@"date"]; //????
    timePicker.date = data[@"date"]; //????
}

- (IBAction) changeDate:(id)sender {
    UIDatePickerView *dp = (UIDatePickerView *)sender;
    [data setObject:dp.date forKey:@"date"]; //????
}

- (IBAction) changeTime:(id)sender {
    UIDatePickerView *tp = (UIDatePickerView *)sender;
    [data setObject:tp.date forKey:@"date"]; //????
}

我不知道如何编码的部分由//????表示。我已经在一些答案中读到NSDateFormatterNSCalendar和某种日期组件,但这实际上让我更加困惑,因为它还会将字符串和结构组合在一起,是什么用来做什么和何时做。请帮忙。

2 个答案:

答案 0 :(得分:1)

你可以尝试这个

///将完整日期转换为仅日期

- (IBAction) changeDate:(UIDatePickerView *)sender {

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:@"MM/dd/yyyy"];
 NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
 [data setObject:dateStr forKey:@"date"];
}

///将日期转换为时间格式

- (IBAction) changeTime:(UIDatePickerView *)sender {

 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
 [dateFormatter setDateFormat:@"hh:mm a"];
 NSString *dateStr = [dateFormatter stringFromDate:[sender date]];
 [data setObject:dateStr forKey:@"Time"];
}

答案 1 :(得分:1)

您可以将两个日期选择器设置为相同的日期和时间。未使用的部分在那里,但不显示,无法更改。当用户更改一个日期选择器的值时,您必须将另一个日期选择器设置为相同的值。

- (IBAction)changeDate:(id)sender {
    NSDatePicker *dp = (NSDatePicker *)sender;
    [data setObject:dp.dateValue forKey:@"date"];
    self.timePicker.dateValue = dp.dateValue;
}

- (IBAction)changeTime:(id)sender {
    NSDatePicker *tp = (NSDatePicker *)sender;
    [data setObject:tp.dateValue forKey:@"date"];
    self.datePicker.dateValue = tp.dateValue;
}