iOS原生UITabBarController添加视图切换动画

1.创建UITabBarController
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    UIViewController *firstViewController = [[FirstViewController alloc] initWithNibName:@"FirstViewController" bundle:nil];
    UIViewController *secondViewController = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];
    self.tabBarController = [[UITabBarController alloc] init];
    self.tabBarController.viewControllers = @[firstViewController, secondViewController];
    self.tabBarController.delegate = self;  // 设置代理
    self.window.rootViewController = self.tabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}
2.设置代理
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController
{
    NSUInteger shouldSelectIndex = [tabBarController.viewControllers indexOfObject:viewController];
    if (tabBarController.selectedIndex == shouldSelectIndex) {
        return YES;
    }

    CATransition *animation = [CATransition animation];
    animation.duration = 0.75;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    if (tabBarController.selectedIndex > shouldSelectIndex) {
        animation.subtype = kCATransitionFromLeft;
    } else {
        animation.subtype = kCATransitionFromRight;
    }
    // 与百度上一般文章不一样
    [[[tabBarController valueForKey:@"_viewControllerTransitionView"] layer] addAnimation:animation forKey:@"animation"];

    return YES;
}
3.区别

在百度的文章里,最后一句设置动画的语句为:

[tabBarController.view.layer addAnimation:animation forKey:@"reveal"];  

这样会导致tabBarController的整个标签栏也跟着一起有动画的效果,这样的效果并不是很好。

当然动画的效果可以自己重新改写,记下以防自己忘记。

你可能感兴趣的:(iOS原生UITabBarController添加视图切换动画)