Question

When you click dateTextField, it shows datePicker with toolBar.
I add doneButton to toolBar, But doneButton is not clickable.
How do I fix it?

    @property (nonatomic, retain) UIDatePicker* datePicker;
    @property (nonatomic, retain) UIToolBar* toolBar;
    @property (nonatomic, retain) UITextField* dateTextField;

    self.datePicker = [[UIDatePicker alloc]init];
    self.datePicker.datePickerMode = UIDatePickerModeTime;
    self.toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, -40, 320, 40)];
    [self.datePicker addSubview:self.toolBar];
    UIBarButtonItem* doneButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(closePicker)];
    NSArray* barItems = [NSArray arrayWithObjects:doneButton, nil];
    [self.toolBar setItems:barItems animated:YES];

    self.dateTextField = [[UITextField alloc]initWithFrame:CGRectMake(90, 5, 100, 25)];
    self.dateTextField.delegate = self;
    self.dateTextField.inputView = self.datePicker;
    [self.view addSubview:self.dateTextField];

Thank you.

Was it helpful?

Solution

Don't add the toolbar as a subview of your date picker. Instead set your dateTextField's inputAccessoryView property to your toolbar (with a normal frame for the toolbar). Something like this:

@property (nonatomic, retain) UIDatePicker* datePicker;
@property (nonatomic, retain) UIToolBar* toolBar;
@property (nonatomic, retain) UITextField* dateTextField;

self.datePicker = [[UIDatePicker alloc]init];
self.datePicker.datePickerMode = UIDatePickerModeTime;


self.toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
UIBarButtonItem* doneButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(closePicker)];
NSArray* barItems = [NSArray arrayWithObjects:doneButton, nil];
[self.toolBar setItems:barItems animated:YES];

self.dateTextField = [[UITextField alloc]initWithFrame:CGRectMake(90, 5, 100, 25)];
self.dateTextField.delegate = self;
self.dateTextField.inputView = self.datePicker;
self.dateTextField.inputAccessoryView = self.toolbar;
[self.view addSubview:self.dateTextField];

Also check out this Apple article for more info:

https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/InputViews/InputViews.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top