Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a UIButton to UIDatePicker

I have a UITextField that I set the inputView to a UIDatePicker so that when the UITextField is pressed, instead of a keyboard, a UIDatePicker pops up. I would like to also add a toolbar with a 'Next' button on it so that the user could easily jump to the next field, but I am not sure how to do this as I am already altering a view on the UITextField to get the UIDatePicker. Here is the code used in loading the view:

- (void)viewDidLoad
{
self.datePicker = [[UIDatePicker alloc] init];
self.datePicker.datePickerMode = UIDatePickerModeDate;
[self.datePicker addTarget:self action:@selector(datePickerValueChanged) forControlEvents:UIControlEventValueChanged];
issue.inputView = self.datePicker;
}

Suggestions for getting the 'Next' button added to a toolbar on top of it?

like image 420
user717452 Avatar asked Nov 30 '25 04:11

user717452


2 Answers

Create a view to use as the text field's inputAccessoryView. This view should contain your buttons (e.g. Next, Cancel, Previous).

like image 157
rmaddy Avatar answered Dec 02 '25 20:12

rmaddy


Here's the code :

if (keyboardToolbar == nil) {
keyboardToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 44)];
[keyboardToolbar setBarStyle:UIBarStyleBlackTranslucent];

UIBarButtonItem *extraSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

UIBarButtonItem *next = [[UIBarButtonItem alloc] initWithTitle:@"Next" style:UIBarButtonItemStyleDone target:self action:@selector(switchToNextField:)];

[keyboardToolbar setItems:[[NSArray alloc] initWithObjects: extraSpace, next, nil]];
}

issue.inputAccessoryView = keyboardToolbar;

datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];

issue.inputView = datePicker;

And in your switchToNextField method, just make the nextField as the firstResponder using [nextTextField becomeFirstResponder];

like image 33
Dhruv Goel Avatar answered Dec 02 '25 18:12

Dhruv Goel