IOS_实现TabBar切换时底部切换效果

来源:互联网 发布:中标麒麟怎么卸载软件 编辑:程序博客网 时间:2024/05/02 00:07

1.首先实现代理方法

#pragma mark -- UITabBarControllerDelegate- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{    UIImageView* slider = (UIImageView*)[self.tabBar viewWithTag:TAB_SLIDER_TAG];        NSUInteger selectedIndex = [self.viewControllers indexOfObjectIdenticalTo:viewController];    if (slider)    {        [self.tabBar bringSubviewToFront:slider];                [UIView beginAnimations:nil context:nil];        [UIView setAnimationDuration:0.2];        CGRect frame = slider.frame;        frame.origin.x = [self horizontalLocationFor:selectedIndex];        slider.frame = frame;        [UIView commitAnimations];    }    else    {        [self addTabBarSliderAtIndex:selectedIndex];    }}

2.步骤1中又两个方法,需要实现下一个是水平移动、一个是更改图片

- (void)addTabBarSliderAtIndex:(NSUInteger)itemIndex{    UIImage* sliderImage = [UIImage imageNamed:@"tab_slider"];    UIImageView* slider = [[UIImageView alloc] initWithImage:sliderImage] ;    slider.tag = TAB_SLIDER_TAG;        slider.frame = CGRectMake([self horizontalLocationFor:itemIndex]                                   , self.tabBar.height - sliderImage.size.height                                   , sliderImage.size.width                                   , sliderImage.size.height);        [self.tabBar addSubview:slider];}- (CGFloat) horizontalLocationFor:(NSUInteger)tabIndex{        CGFloat tabItemWidth = self.tabBar.frame.size.width / self.viewControllers.count;    CGFloat halfTabItemWidth = (tabItemWidth / 2.0) - (_sliderWidth / 2.0);    return (tabIndex * tabItemWidth) + halfTabItemWidth;}