網上的一些定義 tabBar 點擊動畫的做法一般是自定義一個 tabBar 把這個 tabBar 通過 KVC 設置給 tabBarController 然后在這個 tabBar 里做一些自定義。但是tabBar 的實現對我們是未知的,很難保證這種替換方式會不會造成其他的副作用,所以最好的方法就是不去動 tabBar 而是想辦法拿到想要進行動畫的 view。
先通過 Reveal 分析一下 UITabBarController 的 結構:
1.先建一個 Demo 過程,tabBarController 有2個 childViewcontroller,一個有title一個沒有title。
Simulator Screen Shot 2016年9月26日 17.44.31.png
2.通過 Reveal 分析 tabBar 的子控件會發現每個可以點擊的 item 是一個叫“UITabBarButton”的控件,這個控件負責承載圖片和標題文字(如果存在)。
屏幕快照 2016-09-26 17.46.31.jpg
屏幕快照 2016-09-26 17.48.36.jpg
3.3.知道了控件的名字我們就可以在 UITabBarController 的 delegate 方法 - (void)tabBarController:(UITabBarController)tabBarController didSelectViewController:(UIViewController)viewController; 中定位當前點擊的按鈕然后找到對應的圖片了。
- (void)tabBarController:(UITabBarController*)tabBarController didSelectViewController:(UIViewController*)viewController
{
NSMutableArray *tabBarButtonArray = [NSMutableArray array];
[tabBarController.tabBar.subviews enumerateObjectsUsingBlock:^(__kindof UIView*_Nonnull obj,NSUInteger idx,BOOL *_Nonnull stop) {
if([obj isKindOfClass:NSClassFromString(@"UITabBarButton")]) {//先找到所有 UITabBarButton 類型的子控件
[tabBarButtonArray addObject:obj];
}
}];
UIView *tabBarButton = [tabBarButtonArray objectInIndex:tabBarController.selectedIndex];//找到當前被選擇的 button
__block UIImageView *imageView = nil;//找到 button 上的圖片,然后就可以添加動畫了
[tabBarButton.subviews enumerateObjectsUsingBlock:^(__kindof UIView *_Nonnull obj,NSUInteger idx,BOOL *_Nonnull stop) {
if([obj isKindOfClass:[UIImageViewclass]]) {
imageView = obj;
*stop =YES;
}
}];
}