BYLBadgeView 1.0.1

BYLBadgeView 1.0.1

测试已测试
Lang语言 Obj-CObjective C
许可证 MIT
Released最后发布2014年12月

James Richard 维护。



  • 原创
  • James Richard

一个使用 TextKit API 渲染徽章,支持动画和 UIAppearance 的徽章视图。

要求

BYLBadgeView 需要 iOS7+。

安装

使用 Cocoapods

pod 'BYLBadgeView'

要使用而不使用 Cocoapods,请将 Sources 目录下的文件复制到您的项目中。

使用方法

要使用,首先实例化视图并将其添加到您希望放置其中的视图的子视图中。徽章视图计算一个内部内容大小,我建议添加足够的约束将其定位到您希望的位置。以下是将其添加到按钮并将其放置在按钮右上角的方法

BYLBadgeView *badgeView = [[BYLBadgeView alloc] initWithBadge:20];
badgeView.translatesAutoresizingMaskIntoConstraints = NO;
badgeView.opaque = NO;
badgeView.layer.zPosition = 10; // UIButton subviews are added later so we need to ensure this one is in front
[self.badgedButton addSubview:badgeView]; // Created from IB
[self.badgedButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[badgeView]|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(badgeView)]];
[self.badgedButton addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[badgeView]" options:0 metrics:nil views:NSDictionaryOfVariableBindings(badgeView)]];

设置徽章文本颜色

您可以使用徽章 textColor 属性或在 badgeTextAttributes 中设置 NSForegroundColorAttributeName 键来设置徽章文本颜色。徽章 textColor 属性存在是为了允许隐式动画。更多关于动画的信息。

UIAppearance

BYLBadgeView 支持徽章半径、徽章文本属性、徽章背景颜色和徽章文本颜色的 UIAppearance 代理。以下是将样式应用于包含在 UIButton 中的所有徽章的示例

[[BYLBadgeView appearanceWhenContainedIn:[UIButton class], nil] setBadgeBackgroundColor:[UIColor redColor]];
[[BYLBadgeView appearanceWhenContainedIn:[UIButton class], nil] setBadgeTextColor:[UIColor purpleColor]];
[[BYLBadgeView appearanceWhenContainedIn:[UIButton class], nil] setBadgeRadius:10.0f];
NSDictionary *titleAttributes = @{NSFontAttributeName: [UIFont fontWithDescriptor:[UIFontDescriptor preferredFontDescriptorWithTextStyle:UIFontTextStyleSubheadline] size:8.0f]};
[[BYLBadgeView appearanceWhenContainedIn:[UIButton class], nil] setBadgeTextAttributes:titleAttributes];

动画

BYLBadgeView 支持徽章、徽章 textColor、徽章背景颜色和徽章半径属性的隐式动画。以下是一个示例

self.animatingBadgeView.badge = 500; // self.animatingBadgeView was previously instantated
[UIView animateWithDuration:5.0f delay:0.0f options:UIViewAnimationOptionCurveEaseOut | UIViewAnimationOptionRepeat animations:^{
  self.animatingBadgeView.badge = 1000;
  self.animatingBadgeView.badgeTextColor = [UIColor blueColor];
  self.animatingBadgeView.badgeBackgroundColor = [UIColor orangeColor];
} completion:nil];

注意事项

-[NSString drawInRect:withAttributes:] 在设置 textAttributes 字典中的 NSBackgroundColorAttributeName 键时表现异常。因此,如果该键存在于 badgeTextAttributes 字典中,则在设置时将删除它。