8

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

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

有人有想法么?谢谢。

4

3 回答 3

16

我找到了答案!在button action notresponsive 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:)];
于 2012-07-23T02:56:32.270 回答
1

虽然为时已晚,但为了将来的参考,我想引用苹果文档的方法,

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

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

于 2018-08-08T08:09:12.413 回答
0

你试过了吗

-(void)toggleKeyboard

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

它有什么不同吗?方法是否在接口文件中声明?

于 2012-07-22T12:02:19.510 回答