练习: 通过 tabBarItem 上的 badgeValue 修改applicationIconBadgeNumber

本文介绍如何在iOS应用中使用Swift通过观察者模式来动态更新TabBarItem的角标值,并展示了如何在AppDelegate中实现观察者触发逻辑,以及设置应用图标角标的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

@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"];
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值