Wednesday, May 29, 2013

UIActionSheet showFromTabBar example in Objective C (iOS).

UIActionSheet showFromTabBar

Displays an action sheet that originates from the specified tab bar.

- (void)showFromTabBar:(UITabBar *)view

Parameters of [UIActionSheet showFromTabBar]
The tab bar from which the action sheet originates.

Discussion of [UIActionSheet showFromTabBar]
The appearance of the action sheet is animated.

On iPad, this method centers the action sheet in the middle of the screen. Generally, if you want to present an action sheet relative to a tab bar in an iPad application, you should use the showFromRect:inView:animated: method instead.

UIActionSheet showFromTabBar example.
YourAppDelegate *delegate = [[UIApplication sharedApplication] delegate];
[actionSheet showFromTabBar:delegate.tabBarController.tabBar]

Example of [UIActionSheet showFromTabBar].
-(BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController{
    if (!_testInProgress) return YES;
    // If trying to select this controller then who cares?
    if (viewController == self) return YES; // Or NO. Just don't show the sheet.
    UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:@"You are in the middle of a test. Are you sure you want to switch tabs?"
                                               cancelButtonTitle:@"Continue Test"
                                          destructiveButtonTitle:@"Abort Test"
    // Lets cheat and use the tag to store the index of the desired view controller.
    action.tag = [self.tabBarController.viewControllers indexOfObject:viewController];
    [action showFromTabBar:self.tabBarController.tabBar];
    return NO;

UIActionSheet showFromTabBar example.
// For detecting taps outside of the alert view
-(void)tapOut:(UIGestureRecognizer *)gestureRecognizer {
    CGPoint p = [gestureRecognizer locationInView:self];
    if (p.y < 0) { // They tapped outside
        [self dismissWithClickedButtonIndex:0 animated:YES];

-(void) showFromTabBar:(UITabBar *)view {
    [super showFromTabBar:view];

    // Capture taps outside the bounds of this alert view
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapOut:)];
    tap.cancelsTouchesInView = NO; // So that legit taps on the table bubble up to the tableview
    [self.superview addGestureRecognizer:tap];
    [tap release];

End of UIActionSheet showFromTabBar example article.