使用initWithCustomView创build的UIBarButtonItem不会触发操作

我正在更新一些旧的代码,并在工具栏中留出更多空间,我将button从testing转换为图像。 loadView中新旧代码的一个例子是:

// New code, doesn't work. UIButton *toggleKeyboardBtn = [UIButton buttonWithType:UIButtonTypeCustom]; toggleKeyboardBtn.bounds = CGRectMake( 0, 0, showKeyboardImage.size.width, showKeyboardImage.size.height ); [toggleKeyboardBtn setImage:showKeyboardImage forState:UIControlStateNormal]; UIBarButtonItem *toggleKeyboardItem = [[UIBarButtonItem alloc] initWithCustomView:toggleKeyboardBtn]; [toggleKeyboardItem setTarget:self]; [toggleKeyboardItem setAction:@selector(toggleKeyboard:)]; // Original code, works jut fine. UIBarButtonItem *setupItem = [[[UIBarButtonItem alloc] initWithTitle:@"Setup" style:UIBarButtonItemStyleBordered target:[UIApplication sharedApplication].delegate action:@selector(showSetupView:)] autorelease]; 

我的新代码是从UIBarButtonItem无法设置操作 ,我相当肯定,我没有犯错,因为我的文本button工作得很好。

showSetupView()在我的AppController.m文件中,当button被按下时,安装屏幕出现并消失。

toggleKeyboard(),OTOH与loadView()例程位于同一个文件中,目前由以下代码组成:

 //- (void)toggleKeyboard { - (IBAction)toggleKeyboard:(id)sender { NSLog(@"Entering toggleKeyboard()..."); hiddenKeyboard = !hiddenKeyboard; [self prepareToolbarsAndStatusbar]; } 

不用说,虽然我看到button按下animation,我从来没有看到NSLog消息。 最后一个意外发现。 将setActionselect器更改为:

 [toggleKeyboardItem setAction:@selector(noSuchRoutine:)]; 

干净地编译,可能表明我的例程名称由于某种原因被忽略。

有人有主意吗? 谢谢。

我find了答案! 在button操作没有响应的iPhone ,据说动作和目标需要设置在UIButton ,而不是UIBarButtonItem 。 我不知道最新版本的Xcode是否是新的,但我想这是因为其他问题(如上面提到的那个)使用不同的技术。 这是我的新代码:

 UIButton *toggleKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom]; toggleKeyboardButton.bounds = CGRectMake( 0, 0, keyboardAddImage.size.width, keyboardAddImage.size.height ); [toggleKeyboardButton setImage:keyboardAddImage forState:UIControlStateNormal]; [toggleKeyboardButton addTarget:self action:@selector(toggleKeyboard) forControlEvents:UIControlEventTouchUpInside]; UIBarButtonItem *toggleKeyboardItem = [[UIBarButtonItem alloc] initWithCustomView:toggleKeyboardButton]; //[toggleKeyboardItem setTarget:self]; //[toggleKeyboardItem setAction:@selector(toggleKeyboard:)]; 

你试过了吗

-(void)toggleKeyboard

[toggleKeyboardItem setAction:@selector(toggleKeyboard)]; 没有:

它有什么区别? 该方法是在接口文件中声明的?