关于在UIimageView和UIButton右上方添加一个小红点好用的方法
在网上找了很多的方法,积累了一些今后可能用的一些封装好的功能,在这里记录一下,第一次写,感觉很好用,很多快捷编辑的方法,话不多说,上代码。
#import <UIKit/UIKit.h>
@interface UIButton (ZFBadge)
//-- 角标显示的信息,可以为数字和文字(在设置其他属性之前,请务必先设置此属性!)
@property (nonatomic) NSString *badgeValue;
//-- 角标数字改变时是否使用动画(默认YES)
@property (nonatomic, assign) BOOL badgeAnimated;
//-- 角标宽/高最小值(默认8)
@property (nonatomic, assign) CGFloat badgeMinSize;
//-- 角标内容距离其角标控件左右边距距离(默认6)
@property (nonatomic, assign) CGFloat badgePadding;
//-- 角标文字颜色
@property (nonatomic, strong) UIColor *badgeTextColor;
//-- 角标背景色
@property (nonatomic, strong) UIColor *badgeBackgroundColor;
//-- 角标字体
@property (nonatomic, strong) UIFont *badgeFont;
@end
#import "UIButton+ZFBadge.h"
#import <objc/runtime.h>
static const void *kBadgeValueTag = @"kBadgeValueTag";
static const void *kBadgeLabelTag = @"kBadgeLabelTag";
static const void *kBadgeMinSizeTag = @"kBadgeMinSizeTag";
static const void *kBadgePaddingTag = @"kBadgePaddingTag";
static const void *kBadgeTextColorTag = @"kBadgeTextColorTag";
static const void *kBadgeBackgroundColorTag = @"kBadgeBackgroundColorTag";
static const void *kBadgeFontTag = @"kBadgeFontTag";
static const void *kBadgeAnimatedTag = @"kBadgeAnimatedTag";
static const void *kbadgePointPaddingTag = @"kbadgePointPaddingTag";
@interface UIButton ()
//-- 显示角标的控件
@property (nonatomic, weak) UILabel *badgeLabel;
//-- 此参数是为了当角标设置为红点时,红点显示位置不正确而设置的偏移量
@property (nonatomic) CGFloat badgePointPadding;
@end
@implementation UIButton (ZFBadge)
- (void)commonInit
{
self.clipsToBounds = NO;
self.badgeMinSize = 8.f;
self.badgePadding = 6.f;
self.badgeAnimated = YES;
self.badgeTextColor = [UIColor whiteColor];
self.badgeBackgroundColor = [UIColor redColor];
self.badgeFont = self.badgeFont? self.badgeFont : ([UIFont systemFontOfSize:13.f]);
self.badgePointPadding = self.badgePointPadding? self.badgePointPadding : 0;
UILabel *badgeLabel = [[UILabel alloc] init];
badgeLabel.textAlignment = NSTextAlignmentCenter;
[self addSubview:badgeLabel];
self.badgeLabel = badgeLabel;
[self updateBadgeLabel];
}
- (void)updateBadgeLabel
{
UILabel *badgeLabel = self.badgeLabel;
badgeLabel.text = self.badgeValue;
badgeLabel.textColor = self.badgeTextColor;
badgeLabel.backgroundColor = self.badgeBackgroundColor;
badgeLabel.font = self.badgeFont;
[badgeLabel sizeToFit];
CGSize expectedSize = badgeLabel.frame.size;
CGFloat minWidth = expectedSize.width;
CGFloat minHeight = expectedSize.height;
// 根据设置的最小值,重新设置角标高度,并且如果宽度<高度,那么让角标宽度=高度,防止切圆角的时候切错
mi