@implementation DemoViewController
// 1:
- (IBAction)buttonAction:(id)sender {
// 获取当前 tabBarItem 的角标值
NSInteger currentCount = [self.tabBarItem.badgeValue integerValue];
currentCount++;
// 再次设置角标
self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%ld",currentCount];
//2
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
// 第一步:给当前对象添加观察者
[self.tabBarItem addObserver:[UIApplication sharedApplication].delegate forKeyPath:@"badgeValue" options:NSKeyValueObservingOptionNew context:NULL];
}
// Appdelegate
@implementation AppDelegate
// 第二步:触发,观察者
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
// object,被观察者
// change:字典
NSLog(@"----object = %@,change = %@",object,change);
// 更改程序的角标, NSNumber(字典里面没有基础类型)
[UIApplication sharedApplication].applicationIconBadgeNumber = [change[@"new"] integerValue];
}
// 程序的入口
// 这段代码只在 iOS8之后才设置
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// 保存基于系统级别的通知的设置
UIUserNotificationSettings *setting =[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories: nil];
// 通过 application 告诉系统, 你对该 app 的设置
[application registerUserNotificationSettings:setting];
return YES;
}
// 3.
- (void)dealloc {
// 移除观察者
[self.tabBarItem removeObserver:[UIApplication sharedApplication].delegate forKeyPath:@"badgeValue"];
}
}
练习: 通过 tabBarItem 上的 badgeValue 修改applicationIconBadgeNumber
最新推荐文章于 2017-07-31 17:47:01 发布