我正在尝试实现一个自定义导航栏按钮项,当用户单击以调用一个函数时,我有一个选择器。如果我将栏项目设置为UIBarButtonItem
它就可以正常工作,但我必须为按钮使用自定义图像,没有边框和适当的大小。
所以在 viewdidload 我打电话
- (void)viewDidLoad
{
[super viewDidLoad];
//gear button on navigation Bar
UIImage* imageback2 = [UIImage imageNamed:@"ICON - Gear-BarstyleItem@2x.png"];
CGRect frameimgback2 = CGRectMake(0, 0, 40, 40);
UIButton *backButton2 = [[UIButton alloc] initWithFrame:frameimgback2];
[backButton2 setBackgroundImage:imageback2 forState:UIControlStateNormal];
[backButton2 addTarget:self
action:@selector(setColorButtonTapped:)
forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *btn2 = [[UIBarButtonItem alloc] initWithCustomView:backButton2];
UIBarButtonItem *btn3 =[[UIBarButtonItem alloc] initWithImage:imageback2 style:UIBarButtonItemStylePlain target:self action:@selector(setColorButtonTapped:)];
self.navigationItem.rightBarButtonItem = btn2;
}
#pragma mark Callbacks
- (IBAction)setColorButtonTapped:(id)sender{
if (_colorPicker == nil) {
self.colorPicker = [[ColorPickerController alloc] initWithStyle:UITableViewStylePlain];
_colorPicker.delegate = self;
self.colorPickerPopover = [[UIPopoverController alloc] initWithContentViewController:_colorPicker];
}
[self.colorPickerPopover presentPopoverFromBarButtonItem:sender permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
这给了我:
-[UIButton view]: unrecognized selector sent to instance 0x9466620
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIButton view]: unrecognized selector sent to instance 0x9466620'
如果我设置
self.navigationItem.rightBarButtonItem = btn2;
到
self.navigationItem.rightBarButtonItem = btn3;
它工作正常,但按钮有边框和背景颜色和较小的图像尺寸
那么为什么它给我错误,我怎样才能让这个按钮成为一个自定义按钮呢?
编辑:
当我添加一个 void 函数时
- (void)gearTapped{
[self setColorButtonTapped:self];
}
并在按钮处更改选择器它不会给出任何错误,但它只会在屏幕中间显示弹出一行
[backButton2 addTarget:self
action:@selector(gearTapped)
forControlEvents:UIControlEventTouchUpInside];
它通常应该像这样工作,但有一个自定义按钮