当我在选择器 View 上添加工具栏时,工具栏按钮不起作用。它可以在 iOS 6 中运行,但不能在 iOS 7 中运行。
UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0 ,0, 320, 44)];
UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(handleDone)];
UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"Cancel"
style:UIBarButtonItemStyleBordered
target:self
action:@selector(handleCancel)];
UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
target:self
action:nil];
[toolBar setItems:[NSArray arrayWithObjects:cancelButton, flexible, doneButton, nil] animated:YES];
[pikerView addSubview:toolBar];
最佳答案
带有“完成”按钮的 UIToolbar
应添加到成为第一响应者的 View 的 inputAccessoryView
中。由于 UIView
类继承自 UIResponder
,因此任何 View 都可能包含 inputView
和 inputAccessoryView
。因此,您可以使用 UIResponder 的键盘显示/隐藏动画附带的默认动画行为,而不是以编程方式手动执行动画。
子类化
UIView
并覆盖inputView
和inputAccessoryView
属性并使它们可读写
。在此示例中,我将创建UITableViewCell
的子类。// FirstResponderTableViewCell.h @interface FirstResponderTableViewCell : UITableViewCell @property (readwrite, strong, nonatomic) UIView *inputView; @property (readwrite, strong, nonatomic) UIView *inputAccessoryView; @end
在子类的实现中重写
canBecomeFirstResponder
。// FirstResponderTableViewCell.m - (BOOL)canBecomeFirstResponder { return YES; }
在 View Controller 中,创建并分配选取器 View 和输入附件工具栏
// MyViewController.m - (void)viewDidLoad { [super viewDidLoad]; UIPickerView *pickerView = [[UIPickerView alloc] init]; UIToolbar *accessoryToolbar = [UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)]; // Configure toolbar ..... // note: myFirstResponderTableViewCell is an IBOutlet to a static cell in storyboard of type FirstResponderTableViewCell self.myFirstResponderTableViewCell.inputView = pickerView; self.myFirstResponderTableViewCell.inputAccessoryView = accessoryToolbar; }
不要忘记在需要时将第一响应者分配给 View (例如在 -
tableView:didSelectRowAtIndexPath:
内部)[self.myFirstResponderTableViewCell becomeFirstResponder];
希望这有帮助。
引用:http://blog.swierczynski.net/2010/12/how-to-create-uipickerview-with-toolbar-above-it-in-ios/
关于ios - 添加到选择器 View (如附件 View )时,工具栏按钮不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21851012/