廢話不多說甜癞,直接上代碼!
為了不影響系統(tǒng)自帶功能,所以添加一個UITabBarItem
的分類:
// .h 文件
@interface UITabBarItem (Custom)
// 設置角標值時填帽,替換系統(tǒng)的 'setBadgeValue:'方法
- (void)my_setBadgeValue:(NSString *)badgeValue;
@end
// .m 文件
@implementation UITabBarItem (Custom)
- (void)my_setBadgeValue:(NSString *)badgeValue
{
// 先設置角標值
[self setBadgeValue:badgeValue];
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_10_0
// 如果系統(tǒng)是iOS10 以上的就使用系統(tǒng)方法修改
UIColor *badgeColor = [UIColor blueColor];
[self setBadgeColor:badgeColor];
#else
// 這里替換角標顏色的圖片卒密,需要注意的時:這個圖片size=(36px,36px)哲身,圓的
UIImage *badgeImage = [UIImage imageNamed:@"blueBadge"];
[self customBadgeColorWith:badgeImage];
#endif
}
- (void)customBadgeColorWith:(UIImage *)badgeImage
{
UIView *tabBarButton = (UIView *)[self performSelector:@selector(view)];
// iOS10以下的版本 角標其實是一張圖片,所以我們一直找下去這個圖片宠进,然后替換他
for(UIView *subview in tabBarButton.subviews) {
NSString *classString = NSStringFromClass([subview class]);
if([classString rangeOfString:@"UIBadgeView"].location != NSNotFound) {
for(UIView *badgeSubview in subview.subviews) {
NSString *badgeSubviewClassString = NSStringFromClass([badgeSubview class]);
if([badgeSubviewClassString rangeOfString:@"BadgeBackground"].location != NSNotFound) {
[badgeSubview setValue:badgeImage forKey:@"image"];
}
}
}
}
}