廢話很少說,直接上代碼!bash
爲了避免影響系統自帶功能,因此添加一個UITabBarItem
的分類:ui
// .h 文件
@interface UITabBarItem (Custom)
// 設置角標值時,替換系統的 '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
// 若是系統是iOS10 以上的就使用系統方法修改
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"];
}
}
}
}
}
複製代碼