3
votes

I'd like to detect touches (or just a tap would do) on the background to the UIToolbar supplied by a UINavigationController. Things I have tried that don't work (or that I couldn't get to work):

  • adding a UITapGestureController to the UIToolbar - this fails because although it does detect the tap, it consumes touches so the buttons on the toolbar stop working (as they receive no touches)
  • setting a target and action on a UIBarButtonItem that is a UIBarButtonSystemItemFlexibleSpace - flexible spaces don't appear to pick up touches (which seems fair enough)

What I want is to detect any touch that is not on a button. Given that I can't set the toolbar for the UINavigationController (it is read only), so I can't substitute my own UIToolbar subclass, is there a trick / workaround that I am missing?

1
Couldn't you add a big button and set its z-value to lowest? UIToolbar is a UIView, so you should be able to.user684934

1 Answers

4
votes

The following code does the trick:

CGSize toolbarSize = [[[self navigationController] toolbar] frame].size;
UIControl* backgroundControl = [[UIControl alloc] initWithFrame: CGRectMake(0, 0, toolbarSize.width, toolbarSize.height)];
[backgroundControl addTarget:self action:@selector(toolbarBackgroundTap) forControlEvents:UIControlEventTouchDown];
[backgroundControl setAutoresizingMask: [[[self navigationController] toolbar] autoresizingMask]];
[[[self navigationController] toolbar] insertSubview:backgroundControl atIndex:0];
[backgroundControl release];

@bdares - thanks for the suggestion in your comment. That was very helpful.