我有一个 UIPickerView,它在父 View 的加载中附加了一个 UIToolbar,代码如下:
- (void)viewDidLoad {
[super viewDidLoad];
self.itemSortPicker.hidden = false;
pickerData = @[@"Name",@"Item Level",@"Crafting Level",@"Profit",@"Profit Percentage",@"Sell Price",@"Buy Price",@"Supply",@"Demand",@"Rarity"];
self.itemSortPicker.dataSource = self;
self.itemSortPicker.delegate = self;
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
pickerToolbar.barStyle = UIBarStyleDefault;
[pickerToolbar sizeToFit];
[pickerToolbar setFrame:CGRectMake(0, -pickerToolbar.bounds.size.height, 320, 44)];
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(pickerCancel)];
[barItems addObject:cancelBtn];
UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
[barItems addObject:flexSpace];
UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(pickerDone)];
[barItems addObject:doneBtn];
[pickerToolbar setItems:barItems animated:YES];
CGRect pickerRect = self.itemSortPicker.bounds;
self.itemSortPicker.bounds = pickerRect;
self.itemSortPicker.frame = CGRectMake(0, 44, 320, 216);
[self.itemSortPicker addSubview:pickerToolbar];
}
现在的问题是,当我点击“完成”或“取消”按钮时,相关方法不会触发。该方法不接受任何参数,只执行 NSLog 操作。 PickerView 没有从栏中获取焦点,因为当我点击并拖动按钮时,PickerView 没有改变。
最佳答案
问题是 UIToolbar
并不完全在 UIPickerView
的框架内。在编写代码时,虽然 UIToolbar
是 UIPickerView
的 subview ,但工具栏是 -pickerToolbar.bounds.size.height
在 UIPickerView
:
[pickerToolbar setFrame:CGRectMake(0, -pickerToolbar.bounds.size.height, 320, 44)];
因此您无法与其按钮进行交互,因为它悬卡在其父 View 框架的边缘之外。例如,如果您像这样更改了 pickerToolbar 框架:
[pickerToolbar setFrame:CGRectMake(0, 0, 320, 44)];
您应该能够与之互动。
不过,如果您需要在 UIPickerView
上方放置此特定位置 -pickerToolbar.bounds.size.height
,我建议不要将其作为 subview 添加到 UIPickerView
并将其适本地放置为 UIPickerView
的父 View 的 subview 。一般来说,如果您需要与 subview 交互,它需要完全在其父 View 的框架内。
编辑:在这种情况下,如果您要改为将工具栏添加到父 View ,如下所示:
[self.view addSubview:pickerToolbar];
我建议试用此框架以保持您的原始位置:
[pickerToolbar setFrame:CGRectMake(self.itemSortPicker.frame.origin.x, self.itemSortPicker.frame.origin.y - pickerToolbar.bounds.size.height, 320, 44)];
(为了计算这个新框架,我将 UIPicker
的 x 和 y 原点值添加到框架的 x 和 y 中,以针对 View 坐标系的变化进行调整。)
关于ios - 动态创建的 UIBarButtonItem 不会在点击时触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27113562/