面试题答案
一键面试实现思路
- 自定义
UITabBarController
的子类。 - 重写
UITabBarController
的transitionCoordinator
相关方法来处理转场动画。 - 在转场动画的代理方法中,添加自定义的动画效果。
主要代码片段
- 自定义
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
的透明度,并设置新的选中索引。