UITabBar小红点(适配iPad)

 

一、解决上面问题可以采取遍历UITabBarButton的方法获取item的宽度

 

CGFloat tabBarItemWidth = 0;
    for (UIView *view in [self subviews]) {
        if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            if (tabBarItemWidth == 0) {
                tabBarItemWidth = view.frame.origin.x;
                NSLog(@"----%f",tabBarItemWidth);
            } else {
                tabBarItemWidth = view.frame.origin.x - tabBarItemWidth;
                break;
            }
        }
    }

 

 

二、自定bageValue适配 iPhone和iPad(系统self.tabBarController.tabBarItem.badgeValue就可以)

1、UITabBar+badge.h

- (void)showBadgeOnItemIndex:(int)index;   //显示小红点

- (void)hideBadgeOnItemIndex:(int)index; //隐藏小红点

 

2、UITabBar+badge.m

*
 *使用需要设置参数  tabbar的个数
 
 */
#define TabbarItemNums 4   //tabbar的数量 如果是5个设置5
@implementation UITabBar (badge)

//显示小红点
- (void)showBadgeOnItemIndex:(int)index{
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    //新建小红点
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 5;//圆形
    badgeView.backgroundColor = [UIColor redColor];//颜色:红色
   
    
    CGFloat tabBarItemWidth = 0;
    for (UIView *view in [self subviews]) {
        if ([view isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            if (tabBarItemWidth == 0) {
                tabBarItemWidth = view.frame.origin.x;
                NSLog(@"----%f",tabBarItemWidth);
            } else {
                tabBarItemWidth = view.frame.origin.x - tabBarItemWidth;
                break;
            }
        }
    }
    
    
    //计算iPad两边的宽度
    CGFloat Padding = (kScreenWidth-tabBarItemWidth*TabbarItemNums)/2;

    //计算小红点的xy坐标 (0.6  0.1属于百分比可以自己定义)
    CGFloat x = Padding + index*tabBarItemWidth +tabBarItemWidth*0.6;
    CGFloat y = 0.1 *  self.frame.size.height;

    badgeView.frame = CGRectMake(x, y, 10, 10);//圆形大小为10
    [self addSubview:badgeView];
    
 
}




//隐藏小红点
- (void)hideBadgeOnItemIndex:(int)index{
    //移除小红点
    [self removeBadgeOnItemIndex:index];
}

//移除小红点
- (void)removeBadgeOnItemIndex:(int)index{
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        if (subView.tag == 888+index) {
            [subView removeFromSuperview];
        }
    }
}


/*
 *使用时:
 *显示
 *[self.tabBarController.tabBar showBadgeOnItemIndex:2];
 *隐藏
 *[self.tabBarController.tabBar hideBadgeOnItemIndex:2]
 *
 */

 

posted @ 2016-04-12 14:15  索马里猫  阅读(540)  评论(0编辑  收藏  举报