iOS 自定义Tabbar实现push动画隐藏效果

http://wonderffee.github.io/blog/2013/08/07/hide-custom-tab-bar-with-animation-when-push/git

 

在以前的一篇文章(连接)中我写到了没有用UITabbarController来实现一个自定义Tabbar,固然功能也简陋了点。注意到在Weico或微信中的自定义tabbar有一个这样的功能:push到下一个页面时tabbar会被自动隐藏,下面我就来讲说如何使我前面作的自定义tabbar也能实现隐藏。github

若是是原生的tabbar,这个功能实现很容易。在iOS中,每一个UIViewController都有一个属性hidesBottomBarWhenPushed,每次push一个viewController时,设置viewController. hidesBottomBarWhenPushed=YES就能够自动实现前面所说的隐藏功能。可是前提是必须使用UITabbarController,我这里实现的自定义tab bar彻底没有使用UITabbarController,那就要多费点心。微信

若是要实现自定义tabbar在每次push viewController时隐藏,很显然咱们须要push时有事件可以通知自定义tab bar隐藏。若是你熟悉UINavigationController的push流程的话,应该就知道咱们可让UINavigationController执行 push时调用navigationController: willShowViewController:方法来触发通知,前提是要遵照UINavigationControllerDelegate协议。 因为hidesBottomBarWhenPushed是每一个UIViewController都有的属性,咱们姑且仍是把它用上。代码以下:ide

Here’s Code 动画

1
2 3 4 5 6 7 8 9 10 
- (void)navigationController:(UINavigationController *)navigationController  willShowViewController:(UIViewController *)viewController  animated:(BOOL)animated {  if (viewController.hidesBottomBarWhenPushed) {  self.tabBar.hidden = YES;  } else {  self.tabBar.hidden = NO;  } } 

这样的实现是比较简单的。对比weico或微信iPhone应用的自定义tab bar push隐藏行为,你就会发现它们有一个天然的过滤动画来实现隐藏,并且与viewController的push动画同步,这是上面的代码作不到的。若是要实现这个动画,就须要对self.tabbar设置frame的过渡动画,代码以下:spa

Here’s Code code

1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 
- (void)navigationController:(UINavigationController *)navController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {  if (viewController.hidesBottomBarWhenPushed)  {  [self hideTabBar];  }  else  {  [self showTabBar];  } }  - (void)hideTabBar {  if (!tabBarIsShow)  { //already hidden  return;  }  [UIView animateWithDuration:0.35  animations:^{  CGRect tabFrame = tabBar.frame;  tabFrame.origin.x = 0 - tabFrame.size.width;  tabBar.frame = tabFrame;  }];  tabBarIsShow = NO; }  - (void)showTabBar {  if (tabBarIsShow)  { // already showing  return;  }  [UIView animateWithDuration:0.35  animations:^{  CGRect tabFrame = tabBar.frame;  tabFrame.origin.x = CGRectGetWidth(tabFrame) + CGRectGetMinX(tabFrame);  tabBar.frame = tabFrame;  }];  tabBarIsShow = YES; } 

上面代码中的0.35秒这个时间保证了与tabbar的隐藏动画与viewController的push动画同步,基本上能够实现以假乱真的效果。blog

代码连接:https://github.com/wonderffee/idev-recipes/tree/master/CustomTabBar事件

相关文章
相关标签/搜索