Date picker should appear when a button is clicked
hi i am new to iphone/ipad programming .This program i will be doing for ipad so i wanted help My question is by clicking a button can date picker appear and the when the date is chosen , i want it to开发者_开发知识库 be stored in a text field , or is it better to insert a calender instead of date picker ? If so how can i add a normal calender and how to code it
what changes should i do in a nib file ?? will the date will be shown in the text field ?? shouldnt there be a UITextField ??
You would create an IBAction for your button to call to show the UIDatePicker. Then implement the UIDatePicker delegate methods and set the text of your label.
In your header file:
-(IBAction)showDatePicker:(id)sender;
In your implementation file
-(IBAction)showDatePicker:(id)sender
{
UIDatePicker* picker = [[UIDatePicker alloc] init];
picker.autoresizingMask = UIViewAutoresizingFlexibleWidth;
picker.datePickerMode = UIDatePickerModeDate;
[picker addTarget:self action:@selector(dueDateChanged:) forControlEvents:UIControlEventValueChanged];
CGSize pickerSize = [picker sizeThatFits:CGSizeZero];
picker.frame = CGRectMake(0.0, 250, pickerSize.width, 460);
picker.backgroundColor = [UIColor blackColor];
[self.view addSubview:picker];
[picker release];
}
-(void) dueDateChanged:(UIDatePicker *)sender {
NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
//self.myLabel.text = [dateFormatter stringFromDate:[dueDatePickerView date]];
NSLog(@"Picked the date %@", [dateFormatter stringFromDate:[sender date]]);
}
//Later when you need to, just call removeFromSuperView to remove it.
In .h file just Create
UIDatePicker *datePicker;
After that .m file
// For Date
datePicker = [[UIDatePicker alloc]init];
datePicker.datePickerMode = UIDatePickerModeDate;
[_closingDateTxtFld setInputView:datePicker];
UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
[toolBar setTintColor:[UIColor grayColor]];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStylePlain target:self action:@selector(ShowSelectedDate)];
UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
[toolBar setItems:[NSArray arrayWithObjects:space,doneBtn, nil]];
[_closingDateTxtFld setInputAccessoryView:toolBar];
Just call this method
-(void)ShowSelectedDate
{
NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
[formatter setDateFormat:@"YYYY-M-dd"];
if ([_closingDateTxtFld isFirstResponder])
{
_closingDateTxtFld.text=[NSString stringWithFormat:@"%@", [formatter stringFromDate:datePicker.date]];
[_closingDateTxtFld resignFirstResponder];
}
}
精彩评论