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事件

相關文章
相關標籤/搜索