MST

星途 面试题库

面试题:Objective-C实现iOS标签栏切换动画效果

使用Objective-C,如何自定义iOS标签栏(UITabBar)切换时的动画效果?请描述实现思路,并给出主要代码片段。
22.2万 热度难度
编程语言Objective-C

知识考点

AI 面试

面试题答案

一键面试

实现思路

  1. 自定义 UITabBarController 的子类。
  2. 重写 UITabBarControllertransitionCoordinator 相关方法来处理转场动画。
  3. 在转场动画的代理方法中,添加自定义的动画效果。

主要代码片段

  1. 自定义 UITabBarController 子类,例如 CustomTabBarController
#import <UIKit/UIKit.h>

@interface CustomTabBarController : UITabBarController

@end
#import "CustomTabBarController.h"

@implementation CustomTabBarController

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForTransitionFromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC {
    // 这里返回自定义的动画控制器
    return nil;
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
    NSInteger fromIndex = self.selectedIndex;
    NSInteger toIndex = [self.tabBar.items indexOfObject:item];
    if (fromIndex == toIndex) {
        return;
    }
    
    UIViewController *fromVC = self.viewControllers[fromIndex];
    UIViewController *toVC = self.viewControllers[toIndex];
    
    [self transitionFromViewController:fromVC
                      toViewController:toVC
                              duration:0.3
                               options:UIViewAnimationOptionCurveEaseInOut
                            animations:^{
                                // 这里添加自定义动画,例如渐变
                                fromVC.view.alpha = 0;
                                toVC.view.alpha = 1;
                            }
                            completion:^(BOOL finished) {
                                if (finished) {
                                    fromVC.view.alpha = 1;
                                    self.selectedIndex = toIndex;
                                }
                            }];
}

@end

在上述代码中:

  • animationControllerForTransitionFromViewController:toViewController: 方法用于返回自定义的动画控制器,这里暂时返回 nil,实际可自定义动画控制器类来处理复杂动画。
  • tabBar:didSelectItem: 方法在用户点击 UITabBarItem 时触发,在这里实现了简单的渐变动画。首先获取当前选中的索引和新点击的索引,若相同则不处理。然后获取对应的 UIViewController,通过 transitionFromViewController:toViewController:duration:options:animations:completion: 方法来执行自定义动画。动画结束后,恢复 fromVC 的透明度,并设置新的选中索引。