我有一个显示日期的UILabel和一个可以更改UILabel中日期的UIDatePicker。如何在故事板中更改视图时“保存”所选日期,因此当我使用UILabel返回视图时,选择的日期仍然保存而不是恢复到今天的日期?以下是显示NSDate的UIDatePicker和UILabel的代码:
- (void)flatDatePicker:(FlatDatePicker*)datePicker dateDidChange:(NSDate*)date {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSCalendar *coptic = [[NSCalendar alloc] initWithCalendarIdentifier:@"coptic"];
[dateFormatter setCalendar:coptic];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
if (datePicker.datePickerMode == FlatDatePickerModeDate) {
[dateFormatter setDateFormat:@"EEEE, MMMM, dd, yyyy"];
} else if (datePicker.datePickerMode == FlatDatePickerModeDate) {
[dateFormatter setDateFormat:@"HH:mm:ss"];
} else {
[dateFormatter setDateFormat:@"EEEE, MMMM, dd, yyyy HH:mm:ss"];
}
NSString *value = [dateFormatter stringFromDate:date];
self.labelDateSelected.text = value;
}
答案 0 :(得分:1)
您可以将NSDate存储在变量中。然后在viewWillDisappear中保存日期:
-(void)viewWillDisappear:(BOOL)animated {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:lastPickedDate forKey:@"lastDate"];
}
然后,当您返回此屏幕时,您可以验证是否保存了日期并在viewDidLoad或viewDidAppear中恢复它。
-(void)viewDidLoad {
//another code
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDate *date = [defaults objectForKey:@"lastDate"];
if(date) {
_datePicker.date = date;
}
}