zoey
zoey

Reputation: 73

UIDatePicker not updating UILabel

I have a UIDatePicker and trying to update a UILabel in realtime based on the date selected by a user. If the user selects one date (say Jan 21st 2012) and then changes their mind to (say March 21st 2013) I want the UILabel to reflect the change.

So far, the UILabel just reflects the current date and does not update it's text even after the user has selected another date from the UIDatePicker. I have also searched around pointers to fix this but to no avail. Any help will be appreciated. Thanks.

Code so far: .h file, I have

@property (strong, nonatomic) IBOutlet UILabel *entryDateSetLabel;
@property (strong, nonatomic) IBOutlet UIDatePicker *entryDateSelected;

- (IBAction)datePickerDateChanged:(id)sender;

the datePickerDateChanged is hooked up to the value changed event for the date picker

the .m file,

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.entryDateSelected = [[UIDatePicker alloc] init];

    [self.entryDateSelected addTarget:self action:@selector(datePickerDateChanged:) forControlEvents:UIControlEventValueChanged];
}

- (IBAction)datePickerDateChanged:(id)sender {

    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
    [outputFormatter setDateFormat:@"MMMM d, yyyy"];

    NSString *entryDateInString = [outputFormatter stringFromDate:self.entryDateSelected.date];

    [[self entryDateSetLabel] setText: entryDateInString];
}

Screenshots

enter image description here enter image description here

Upvotes: 0

Views: 2507

Answers (2)

zoey
zoey

Reputation: 73

Just fixed the problem. :-)

The viewDidLoad should read

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSDate *now = [NSDate date];
    [_entryDateSelected setDate:now animated:YES];

     //self.entryDateSelected = [[UIDatePicker alloc] init];

    [self.entryDateSelected addTarget:self action:@selector(datePickerDateChanged:) forControlEvents:UIControlEventValueChanged];
}

Hope this helps someone else out there.

Upvotes: 0

Vishal
Vishal

Reputation: 556

connect data picker at "Value change" event and

use this code i copied it from other so u have to done some changes

NSDate *today1 = pkrViewDate.date;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MMMM dd, yyyy"];
NSString *dateString11 = [dateFormat stringFromDate:today1];
lblDate.text=dateString11;

ans also check that when you scroll datepicker thn "datePickerDateChanged" method is calling or not.

Upvotes: 2

Related Questions