I\'d like to Display UIDatePicker only when user the UITextField is Clicked. When the date is picked, it should be shown in the same UITextField.I want to implement UIDatePicker
First indicate that your class conforms to the UITextFieldDelegate
protocol
Then in viewDidLoad
set the delegate
and tag
of your text field.
yourTextField.delegate = self;
yourTextField.tag = 111;
Then implement the following delegate method:
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
if (textField.tag==111) {
[self showDatePicker];
}
return YES;
}
Now implement a function showDatePicker
- (void)showDatePicker {
datePicker = [[UIDatePicker alloc] init];
datePicker.backgroundColor=[UIColor whiteColor];
UIToolbar *toolbar = [[UIToolbar alloc]init];
[toolbar sizeToFit];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(showSelectedDate)];
doneBtn.tintColor = [UIColor whiteColor];
UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
toolbar.backgroundColor = [UIColor colorWithRed:5.0/255.0 green:110.0/255.0 blue:170.0/255.0 alpha:1];
[toolbar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft,doneBtn ,nil]];
[yourTextField setInputAccessoryView:toolBar];
yourTextField.inputView = datePicker;
}
OR you can do it simply in your viewDidLoad
as follows:
datePicker = [[UIDatePicker alloc] init];
datePicker.backgroundColor = [UIColor whiteColor];
UIToolbar *toolbar = [[UIToolbar alloc]init];
[toolbar sizeToFit];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self
action:@selector(showSelectedDate)];
doneBtn.tintColor = [UIColor whiteColor];
UIBarButtonItem *flexibleSpaceLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:nil action:nil];
toolbar.backgroundColor = [UIColor colorWithRed:5.0/255.0 green:110.0/255.0 blue:170.0/255.0 alpha:1];
[toolBar setItems:[NSArray arrayWithObjects:flexibleSpaceLeft, doneBtn , nil]];
[yourTextField setInputAccessoryView:toolbar];
yourTextField.inputView = datePicker;