문제

I have a UILabel that displays a date and A UIDatePicker that can change the date in the UILabel. How do I "save" the date selected when changing the view in a storyboard, so when I go back to the view with the UILabel, the date is selected is still saved as opposed to reverting back to todays date? Here is the code for my UIDatePicker and UILabel that displays NSDate:

- (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;
}
도움이 되었습니까?

해결책

You can store the NSDate in a variable. Then in viewWillDisappear you save the date:

-(void)viewWillDisappear:(BOOL)animated {
     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
     [defaults setObject:lastPickedDate forKey:@"lastDate"];
}

Then, when you get back to this screen you can verify if there's a date saved and restore it in viewDidLoad or viewDidAppear.

-(void)viewDidLoad {
     //another code

     NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
     NSDate *date = [defaults objectForKey:@"lastDate"];

     if(date) {
        _datePicker.date = date;
     }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top