Sep 2, 2011

UIActionSheet Cancel Button Not Working

I’m working on a app that has a tab bar with an “Add” button in the middle of that tab bar.

The first step when that “Add” button is hit is to display an UIActionSheet. I found, however, that they “Cancel” button on the action sheet was not clickable. After much confusion, this stack overflow post helped me.

How you display the UIActionSheet is very important. I had copied the Apple NavBar demo that uses it, which used the following code to launch it:


UIActionSheet *styleAlert = [[UIActionSheet alloc] initWithTitle:@"Choose a UIBarStyle:" delegate: self cancelButtonTitle:@"Cancel"
									   destructiveButtonTitle: nil
										otherButtonTitles: @"Default", @"BlackOpaque", @"BlackTranslucent", nil, nil];

[styleAlert showInView:self.view];
[styleAlert release];

The problem is that if you have a UITabBarController, it’s tab bar view takes precedence on the touch (even though the UIActionSheet appears on top), so the Cancel button isn’t actually clicked.

To fix it you need to launch the UIActionSheet differently:


UIActionSheet *styleAlert = [[UIActionSheet alloc] initWithTitle:@"Choose a UIBarStyle:" delegate: self cancelButtonTitle:@"Cancel"
									   destructiveButtonTitle: nil
										otherButtonTitles: @"Default", @"BlackOpaque", @"BlackTranslucent", nil, nil];

// The proper way to do it if there is a tab bar
[typeSelection showFromTabBar:self.tabBarController.tabBar];
[styleAlert release];