美文网首页
iOS UIButton+Badge给你的Button添加数量提

iOS UIButton+Badge给你的Button添加数量提

作者: 木子de李 | 来源:发表于2016-09-27 16:18 被阅读1819次

    我们写代码时经常会遇见需要提示消息数目的Button,去网上找的又不合心意,无奈之下只好自己写了一个类别来用,写的不好,想用的可以试试,不喜勿喷。

    首先给UIButton写一个类别,定义一个对象方法:

    - (void)setBadge:(NSString *)number andFont:(int)font;

    实现如下:

    - (void)setBadge:(NSString *)number andFont:(int)font{

    CGFloat width = self.bounds.size.width;

    CGSize size = [@"1" getSizeOfStringWihtFont:font addMaxSize:CGSizeMake(99, 99)];

    UILabel *badge = [[UILabel alloc] initWithFrame:CGRectMake(width*2/3, -width/4, width/2+(number.length-1)*size.width, width/2)];

    badge.text = number;

    badge.textAlignment = NSTextAlignmentCenter;

    badge.font = [UIFont systemFontOfSize:font];

    badge.backgroundColor = [UIColor redColor];

    badge.textColor = [UIColor whiteColor];

    badge.layer.cornerRadius = width/4;

    badge.layer.masksToBounds = YES;

    [self addSubview:badge];

    }

    然后在外部引入头文件调用方法就可以了:

    [btn setBadge:@"999" andFont:12];

    /**获得字符串的大小*/

    -(CGSize)getSizeOfStringWihtFont:(int)fontSize addMaxSize:(CGSize)maxSize

    {

    CGSize size=[self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin|NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:fontSize]} context:nil].size;

    return size;

    }

    相关文章

      网友评论

          本文标题:iOS UIButton+Badge给你的Button添加数量提

          本文链接:https://www.haomeiwen.com/subject/sfipsttx.html