UIToolBar上的完成按钮无法运行 - iOS

时间:2014-04-23 07:51:07

标签: ios objective-c uipickerview uitoolbar

我正在尝试使用已完成按钮的条创建一个选择器。

我尝试按如下方式实施;

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];

不幸的是,完成按钮不起作用。这段代码有什么问题?

你能帮我吗

1 个答案:

答案 0 :(得分:0)

您首先将按钮添加到视图中。 因此,当您添加日期选择器时,它位于按钮上方。这就是按钮没有响应触摸的原因。 改为:

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];