-1

I am trying to create a picker with bar that has done button.

I tried to implement as follows;

viewForDatePicker = [[UIView alloc]initWithFrame:CGRectMake(0, 300, 320, 266)];

[viewForDatePicker setBackgroundColor:[UIColor whiteColor]];

UIToolbar *toolBar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
toolBar.barStyle = UIBarStyleBlackOpaque;

UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                                                     target:self action:@selector(doneButtonPressed:)];

UIButton * doneButton =[[UIButton alloc]initWithFrame:CGRectMake(290, 2, 30, 20)];
[doneButton setBackgroundColor:[UIColor redColor]];
[doneButton addTarget:self action:@selector(doneButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[viewForDatePicker addSubview:doneButton];

[toolBar setItems:[NSArray arrayWithObject:btn]];
[viewForDatePicker addSubview:toolBar];

birthDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 320, 266)];
[birthDatePicker setDatePickerMode:UIDatePickerModeDate];
[birthDatePicker setBackgroundColor:[UIColor whiteColor]];

[viewForDatePicker addSubview:birthDatePicker];


[self.view addSubview:viewForDatePicker];

Unfortunately done button does not perform. What is wrong with this code?

Could you please help me

erdemgc
  • 11
  • 6

1 Answers1

0

You are adding the button to the view first. So when you add the date picker it is above the button. This is why the button is not responding to touch. Change to this:

birthDatePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 320, 266)];
[birthDatePicker setDatePickerMode:UIDatePickerModeDate];
[birthDatePicker setBackgroundColor:[UIColor whiteColor]];

[viewForDatePicker addSubview:birthDatePicker];

UIButton * doneButton =[[UIButton alloc]initWithFrame:CGRectMake(290, 2, 30, 20)];
[doneButton setBackgroundColor:[UIColor redColor]];
[doneButton addTarget:self action:@selector(doneButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
[viewForDatePicker addSubview:doneButton];

[toolBar setItems:[NSArray arrayWithObject:btn]];
[viewForDatePicker addSubview:toolBar];
CW0007007
  • 5,681
  • 4
  • 26
  • 31