UIBarButtonItem created using initWithCustomView doesn't trigger action

Viewed 9299

I'm updating some old code, and to make more room in a toolbar, I'm converting the Buttons from test to images. An example of the new and old code in loadView is this:

// 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];

My new code is copied from Cannot set action on UIBarButtonItem, and I'm fairly certain that I'm not making their mistake since my text button is working just fine.

showSetupView() is in my AppController.m file, and the setup screen appears and disappears as the button is pressed.

toggleKeyboard(), OTOH, is in the same file as the loadView() routine, and currently consists of this code:

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

Needless to say, although I see the button-press animation, I never see the NSLog message. And one last observation, made by accident. Changing the setAction selector to this:

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

compiles cleanly, possibly indicating that my routine name is being ignored for some reason.

Anyone have any ideas? Thanks.

3 Answers

Though its too late, but for future references, I would like to quote apple docs for the method,

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

The bar button item created by this method does not call the action method of its target in response to user interactions. Instead, the bar button item expects the specified custom view to handle any user interactions and provide an appropriate response.

Related