Search code examples
iosuitabbarcontrolleruitabbaribaction

How to hide tab bar with animation in iOS?


So I have a button that is connected to a IBAction. When I press the button I want to hide the tab bar in my iOS app with a animation. This [self setTabBarHidden:hidden animated:NO]; or this [self.tabBarController setTabBarHidden:hidden animated:YES]; does not work. This is my code without the animation:

- (IBAction)picture1:(id)sender {
    [self.tabBarController.tabBar setHidden:YES];
}

Any help would be greatly appreciated :D


Solution

  • I try to keep view animations available to me using the following formula:

    // pass a param to describe the state change, an animated flag and a completion block matching UIView animations completion 
    - (void)setTabBarVisible:(BOOL)visible animated:(BOOL)animated completion:(void (^)(BOOL))completion {
    
        // bail if the current state matches the desired state
        if ([self tabBarIsVisible] == visible) return (completion)? completion(YES) : nil;
    
        // get a frame calculation ready
        CGRect frame = self.tabBarController.tabBar.frame;
        CGFloat height = frame.size.height;
        CGFloat offsetY = (visible)? -height : height;
    
        // zero duration means no animation
        CGFloat duration = (animated)? 0.3 : 0.0;
    
        [UIView animateWithDuration:duration animations:^{
            self.tabBarController.tabBar.frame = CGRectOffset(frame, 0, offsetY);
        } completion:completion];
    }
    
    //Getter to know the current state
    - (BOOL)tabBarIsVisible {
        return self.tabBarController.tabBar.frame.origin.y < CGRectGetMaxY(self.view.frame);
    }
    
    //An illustration of a call to toggle current state
    - (IBAction)pressedButton:(id)sender {
        [self setTabBarVisible:![self tabBarIsVisible] animated:YES completion:^(BOOL finished) {
            NSLog(@"finished");
        }];
    }