我在iPhone项目中使用了UIDatePicker。我想在打开它之后在datepicker中显示日期,然后单击“完成”按钮。我正在使用此代码:
[datePicker addTarget:self action:@selector(changeDate:) forControlEvents:UIControlEventValueChanged]
changeDate是我在其他地方定义的方法,我在该方法中放入了相应的UIControlEventValueChanged代码。但是,即使我没有做任何更改,我也想在“完成”按钮后显示UIDatePicker中的值。我怎么能这样做?
答案 0 :(得分:2)
您可以使用以下代码....
-(void)showDate{
menu = [[UIActionSheet alloc] initWithTitle:@"Select Date"
delegate:self
cancelButtonTitle:nil
destructiveButtonTitle:nil
otherButtonTitles:nil];
datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0.0, 44.0, 0.0, 0.0)];
datePicker.datePickerMode = UIDatePickerModeDate;
datePicker.minimumDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]autorelease]];
[dateFormatter setDateFormat:@"dd MMM yyyy"];
//[dateFormatter setDateFormat:@"MM/dd/YYYY"];
//[theDatePicker release];
[datePicker addTarget:self action:@selector(LabelChange:) forControlEvents:UIControlEventValueChanged];
dateTool = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
dateTool.barStyle=UIBarStyleBlackOpaque;
[dateTool sizeToFit];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
[barItems addObject:flexSpace];
[dateTool setItems:barItems animated:YES];
[menu addSubview:dateTool];
[menu addSubview:datePicker];
[menu showInView:self.view];
[menu setBounds:CGRectMake(0,0,320, 464)];
// [self.view addSubview:datePicker];
[datePicker release];
}
-(IBAction)DatePickerDoneClick{
[menu dismissWithClickedButtonIndex:0 animated:YES];
}
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
return [arrTime count];
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
return [arrTime objectAtIndex:row];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
txtTime.text = [arrTime objectAtIndex:row];
}