PDA

View Full Version : How to use UIDatePicker




Brendan.Porter
Aug 2, 2008, 02:36 PM
I cannot get my app to return the value from the DatePicker, and it is incredibly frustrating.

Can anyone help with suggestions to create a DatePicker, initialize it, set it to spit out the current selection to an NSString?

I really need help.

Thanks.

Here's what I have so far:

-(void) createPicker
{
myDatePicker = [[UIDatePicker alloc] awakeFromNib];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
theTime= [dateFormatter stringFromDate:[NSDate date]];

}

And I'm currently receiving a warning "void value not ignored as it ought to be"... a warning I was not receiving before today (after changing too much code to remember).



Brendan.Porter
Aug 2, 2008, 03:22 PM
Sorry to reply to my own thread... but here's my revised code.

-(void) awakeFromNib
{
myDatePicker = [[UIDatePicker alloc]init];
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateFormat:(NSString*) @"h:mm a"];
[myDatePicker addTarget:self action:@selector(controlEventValueChanged:) forControlEvents:UIControlEventValueChanged];
theTime = [dateFormatter stringFromDate:[myDatePicker date]];

[theTime retain];
}

- (IBAction) buttonPress: calculateButton
{
timeInField.text = theTime;
}

The above code works to display *THE CURRENT TIME* and NOT the time displayed in the Picker. Progress....

Any help?

forrestgrant
Apr 29, 2009, 01:27 PM
Did you ever find a fix for this? I am having the same issue now.

Niiro13
Apr 29, 2009, 04:03 PM
The reason why your first code doesn't work is that you never should call awakeFromNib (now I can see you fixed it in your second code). Because awakeFromNib doesn't return anything, you're pretty much setting the datepicker object as nil and not an initialized datePicker.

The second code theTime is simply a string that gets the date from the picker then retains the string of that date. Therefore, you receive the same value again and again.

What you should do is move all the dateFormatter stuff into the buttonPress action:

- (IBAction) buttonPress: calculateButton
{

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateFormat:(NSString*) @"h:mm a"];

timeInField.text = [dateFormatter stringFromDate:[myDatePicker date]];
}

If that doesn't work it has something to do with the dateFormat as that's the only one I'm unfamiliar with.