如何在UIBarButtonItem上显示数字(BadgeValue)

原因:项目中想要实现购物车右上角显示购物车中上品数量,但是直接用UIBarButtonItem不能实现要求

这里是实现后的效果图:

购物车动画.gif

一开始直接创建的UIBarButtonItem,但是不能直接往上面添加想要的效果,因为

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIBarButtonItem : UIBarItem 

而且

NS_CLASS_AVAILABLE_IOS(2_0) @interface UIBarItem : NSObject 

退而求其次,我们知道UIBarButtonItem有一个属性

@property(nullable, nonatomic,strong)  __kindof UIView     *customView;       // default is nil

这说明我们可以使用UIButton来代替UIBarButtonItem,在UIButton上面添加想要的动画效果。


    static CGFloat const kButtonWidth = 43.0f;
    static CGFloat const kButtonHeight = 43.0f;
    
    UIImage *cartImage = [[UIImage imageNamed:@"iconfont-cart"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    
    UIButton *cartButton = [UIButton buttonWithType:UIButtonTypeCustom];
    cartButton.frame = CGRectMake(0.0f, 0.0f, kButtonWidth, kButtonHeight);
    cartButton.backgroundColor = [UIColor clearColor];
    [cartButton setImage:cartImage forState:UIControlStateNormal];
    [cartButton setImageEdgeInsets:UIEdgeInsetsMake(0.0f,(kButtonHeight- cartImage.size.width), 0.0f, 0.0f)];
    [cartButton addTarget:self action:@selector(changeStatus:) forControlEvents:UIControlEventTouchUpInside];
    [cartButton addSubview:self.numberLabel];

    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:cartButton];
    self.navigationItem.rightBarButtonItem = rightBarButtonItem;

创建Label使用懒加载:

#pragma mark 购物车上面显示的按钮
-(UILabel *)numberLabel
{
    if (!_numberLabel) {
        
        static CGFloat const kNameLabelWidth = 14;
        static CGFloat const kNameLabelHeight = 14;
        static CGFloat const kNameLabelX = 40; // 父视图宽44,UI说改到这个位置
        static CGFloat const kNameLabelY = 6;
        
        _numberLabel = [UILabel new];
        _numberLabel.hidden = YES;
        _numberLabel.frame = CGRectMake(kNameLabelX, kNameLabelY, kNameLabelWidth, kNameLabelHeight);
        
        _numberLabel.backgroundColor = [UIColor redColor];
        _numberLabel.textColor = [UIColor whiteColor];
        _numberLabel.font = [UIFont systemFontOfSize:9];
        _numberLabel.textAlignment = NSTextAlignmentCenter;
        _numberLabel.layer.cornerRadius = kNameLabelHeight * 0.5;
        _numberLabel.layer.masksToBounds = YES;
        
    }
    return _numberLabel;
}

这里说下为什么设置为hidden,因为要求数量为0的时候不显示,数量不为0显示,如果删除后还要添加不如直接控制hidden。
其他的就是设置Label显示的数字了,这里就不写了。

你可能感兴趣的:(如何在UIBarButtonItem上显示数字(BadgeValue))