UIPickerView工具栏按钮不起作用

时间:2013-11-18 16:59:23

标签: ios7 uipickerview

我正在尝试向UIPicker添加工具栏。 我已经看到了正确的方法:

UIToolbar* toolbarWeight= [[UIToolbar alloc] initWithFrame:CGRectMake(0,0,320,44)];
UIBarButtonItem *barButtonDone1 = [[UIBarButtonItem alloc] initWithTitle:@"Done"
                                                                               style:UIBarButtonItemStyleBordered target:self action:@selector(gotoNextField:)];
[toolbarWeight setItems:[NSArray arrayWithObject:barButtonNext1] animated:YES]; 

weightPickerView = [[UIPickerView alloc]init];
[weightPickerView addSubview:toolbarWeight];

虽然:

-(IBAction)gotoNextField:(id)sender{
    NSLog(@"Works");
}

选择器工作得很好,但按钮不起作用。 做了一些研究之后,我尝试了这种方法: (我怀疑这个问题与UIBarButtonItem动作有关)

UIButton* myBtn = [[UIButton alloc]init];
myBtn.frame = CGRectMake(0,0,50,24);
[myBtn addTarget:self action:@selector(gotoNextField:) forControlEvents:UIControlEventTouchUpInside];
[myBtn setTitle:@"Next!" forState:UIControlStateNormal];
[myBtn setBackgroundColor:[UIColor orangeColor]];
UIBarButtonItem *barButtonNext1 = [[UIBarButtonItem alloc] initWithCustomView:myBtn];
[toolbarWeight setItems:[NSArray arrayWithObject:barButtonNext1] animated:YES];

也不起作用。该按钮出现但未被选中/响应touchUpInside。

2 个答案:

答案 0 :(得分:14)

此处添加包含工具栏的UIPickerView的示例 - 适用于iOS 7

确保实现接口UIPickerViewDataSource,UIPickerViewDelegate并实现@selector方法

pickerView = [[UIPickerView alloc] init];
[pickerView setDataSource: self];
[pickerView setDelegate: self];
pickerView.showsSelectionIndicator = YES;

UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleBordered target:self action:@selector(itemWasSelected:)];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:self action:@selector(logoutData)];
UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
UIBarButtonItem *clearButton = [[UIBarButtonItem alloc] initWithTitle:@"Clear" style:UIBarButtonItemStyleBordered target:self action:@selector(clearData)];
[toolBar setItems:[NSArray arrayWithObjects:cancelButton, clearButton, flexible, doneButton, nil]];

pickerParentView = [[UIView alloc] initWithFrame:CGRectMake(0, 60, 320, 260)];
[pickerParentView addSubview:pickerView];
[pickerParentView addSubview:toolBar];
[self.view addSubview:pickerParentView];

答案 1 :(得分:1)

在向pickerView添加工具栏时,工具栏会添加到选择器后面,防止按钮响应触摸事件。

在视图中封装选择器和工具栏,并使其成为inputView(使选择器和工具栏一起弹出)提供了所需的解决方案。

weightPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 44, 320, 216)];
weightPickerView.tag = 13;
UIView* genericWeightView = [[UIView alloc]initWithFrame:CGRectMake(0, 219, 320, 266)];
[genericWeightView addSubview:toolbarWeight];
[genericWeightView  addSubview:weightPickerView];

然后:

[weight_txtField setInputView:genericWeightView];