UIPickerView选择并隐藏

时间:2011-03-18 02:51:11

标签: iphone ios uipickerview

如何使UIPickerView行为像带有webview的行为,其中有一个下拉选择框,而不是像通常的网站一样下降,iphone使其成为{UIPickerView 1}}包含所有选项。当您选择一个选项时,选项旁边会显示一个检查,并更改下拉框的值。如何将“完成”按钮放在UIPickerView的顶部以关闭UIPickerView

我已经知道[pickerview setHidden:YES]是用于隐藏选择器视图的方法。我只是不知道如何在UIPickerView中添加“完成”按钮。

此致 克里斯

2 个答案:

答案 0 :(得分:34)

这段代码将作为键盘滑出选择器视图,并在其上方附加一个完成按钮。基本上,您希望使用输入字段设置inputAccessoryView。 您应该在输入字段的触地事件中调用此方法。

- (IBAction)showYourPicker:(id)sender {

// create a UIPicker view as a custom keyboard view
UIPickerView* pickerView = [[UIPickerView alloc] init];
[pickerView sizeToFit];
pickerView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
pickerView.delegate = self;
pickerView.dataSource = self;
pickerView.showsSelectionIndicator = YES;
self.yourPickerView = pickerView;  //UIPickerView

yourTextField.inputView = pickerView;

// create a done view + done button, attach to it a doneClicked action, and place it in a toolbar as an accessory input view...
// Prepare done button
UIToolbar* keyboardDoneButtonView = [[UIToolbar alloc] init];
keyboardDoneButtonView.barStyle = UIBarStyleBlack;
keyboardDoneButtonView.translucent = YES;
keyboardDoneButtonView.tintColor = nil;
[keyboardDoneButtonView sizeToFit];

UIBarButtonItem* doneButton = [[[UIBarButtonItem alloc] initWithTitle:@"Done"
    style:UIBarButtonItemStyleBordered target:self
    action:@selector(pickerDoneClicked:)] autorelease];

[keyboardDoneButtonView setItems:[NSArray arrayWithObjects:doneButton, nil]];

// Plug the keyboardDoneButtonView into the text field...
yourTextField.inputAccessoryView = keyboardDoneButtonView;  

[pickerView release];
[keyboardDoneButtonView release];
}

最后,您的完成按钮会调用“pickerDoneClicked”方法,您应该在其中添加 [yourTextField resignFirstResponder];会隐藏选择器视图。

答案 1 :(得分:6)

“完成”按钮放在UIToolBar中。

使用UIToolBar的以下方法添加“完成”按钮。

- (void)setItems:(NSArray *)items animated:(BOOL)animated {

    UIToolbar*  mypickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];
    mypickerToolbar.barStyle = UIBarStyleBlackOpaque;
    [mypickerToolbar sizeToFit];

    NSMutableArray *barItems = [[NSMutableArray alloc] init];

    UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItems addObject:flexSpace];

    UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(DatePickerDoneClick)];
    [barItems addObject:doneBtn];

    [mypickerToolbar setItems:barItems animated:YES];

}