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

时间:2012-07-22 11:15:25

标签: iphone ios xcode uibarbuttonitem

我正在更新一些旧代码,并在工具栏中腾出更多空间,我正在将按钮从测试转换为图像。 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];

我的新代码是从Cannot set action on UIBarButtonItem复制的,而且我很确定我没有犯错,因为我的文本按钮工作正常。

showSetupView()位于我的AppController.m文件中,当按下按钮时,设置屏幕出现并消失。

toggleKeyboard(),OTOH,与loadView()例程在同一个文件中,目前包含以下代码:

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

毋庸置疑,虽然我看到按钮动画,但我从未看到过NSLog消息。最后一次观察是偶然发现的。将setAction选择器更改为:

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

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

有人有什么想法吗?感谢。

3 个答案:

答案 0 :(得分:16)

我找到了答案!在button action not responding 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:)];

答案 1 :(得分:1)

虽然为时已晚,但是为了将来参考,我想引用apple docs作为该方法,

- (instancetype)initWithCustomView:(UIView *)customView;
  

此方法创建的条形按钮项不会调用   目标响应用户交互的操作方法。   相反,条形按钮项期望指定的自定义视图   处理任何用户交互并提供适当的响应。

答案 2 :(得分:0)

你试过吗

-(void)toggleKeyboard

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

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