代码之家  ›  专栏  ›  技术社区  ›  leonho

在iPhone中有没有实现“蓝色徽章”的标准方法?

  •  19
  • leonho  · 技术社区  · 16 年前

    许多iPhone应用程序使用蓝色徽章来指示子视图中的项目数,例如邮件客户端:

    iPhoto http://img.skitch.com/20081103-tjr9yupbhgr3sqfh7u56if4rsn.preview.jpg

    有什么标准方法(甚至是API)可以做到这一点吗?

    更新:我已经创建了一个名为bluebadge的类来执行此操作。它在 http://github.com/leonho/iphone-libs/tree/master

    5 回复  |  直到 13 年前
        1
  •  22
  •   Ben Gottlieb    16 年前

    据我所知,这没有API。但是,使用Coregraphics(iPhone上没有nsbezierPath),您可以很容易地做到这一点。在cgpath中只有两个弧和一些文本:

    CGContextRef        context = UIGraphicsGetCurrentContext();
    float               radius = bounds.size.height / 2.0;
    NSString            *countString = [NSString stringWithFormat: @"%d", count];
    
    CGContextClearRect(context, bounds);
    
    CGContextSetFillColorWithColor(context, ovalColor);
    CGContextBeginPath(context);
    CGContextAddArc(context, radius, radius, radius, M_PI / 2 , 3 * M_PI / 2, NO);
    CGContextAddArc(context, bounds.size.width - radius, radius, radius, 3 * M_PI / 2, M_PI / 2, NO);
    CGContextClosePath(context);
    CGContextFillPath(context);
    
    [[UIColor whiteColor] set];
    
    UIFont              *font = [UIFont boldSystemFontOfSize: 14];
    CGSize              numberSize = [countString sizeWithFont: font];
    
    bounds.origin.x = (bounds.size.width - numberSize.width) / 2;
    
    [countString drawInRect: bounds withFont: font];
    
        2
  •  3
  •   kleinman    16 年前

    我认为一个更好的方法来实现非常接近 UITabBarItem 徽章是用 UIImage stretchableImageWithLeftCapWidth:topCapHeight: 两个端盖都可以是更漂亮的图像,中间将自动拉伸(使用1px宽的图像)以适应 NSString 顶部覆盖的尺寸。

    仍然需要得到正确的图像,但可以很容易地从屏幕截图中提取或从PS构建。

        3
  •  1
  •   Yonat    13 年前

    通过使用简单的uilabel并更改其底层的转弯半径,可以轻松灵活地完成此操作:

    #import <QuartzCore/QuartzCore.h> // don't forget!
    // ...
    UILabel *badge = [[UILabel alloc] init];
    badge.layer.backgroundColor = [UIColor blueColor].CGColor;
    badge.layer.cornerRadius = badge.bounds.size.height / 2;
    

    你可以用我的(小而简单) code for a BadgeLabel class and a matching BadgeTableViewCell class .

        4
  •  0
  •   Kristian    16 年前

    nsbezierPath类中有几个方法称为“AppendBezierPathWithRoundedRect….”。

    我自己也没试过,但它们可能管用。值得一试。

        5
  •  -7
  •   Kristian    16 年前

    还有另一种类型的徽章,您可能已经知道了,它是应用程序图标上的“红色”徽章。它们是通过如下方式创建的:

    NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
    NSString *caldate = [[now 
            dateWithCalendarFormat:@"%b" 
            timeZone:nil] description];
    [self setApplicationBadge:caldate];"
    

    这将为徽章设置当前月份的3个字母缩写。