我的第一个Mac开发笔记(NSUserNotification)

本文详细介绍了如何在iOS应用中创建并使用通知中心,包括创建通知、递交通知、设置代理以及删除已显示通知等关键步骤。

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

首先,我们应该怎样去创建一个通知中心呢?下面我以代码的形式来展示如何构建一个通知中心:

 NSUserNotification *notification = [[NSUserNotification alloc] init];//创建通知中心
  notification.title = @"通知中心";
  notification.subtitle = @"小标题";
  notification.informativeText = @"详细文字说明";
  notification.contentImage = [NSImage imageNamed:@"ladybugThumb.jpg"];
  
  //只有当用户设置为提示模式时,才会显示按钮
  notification.hasActionButton = YES;
  notification.actionButtonTitle = @"确定";
  notification.otherButtonTitle = @"取消";

 一条通知被创建好了,要让该条通知显示给用户,那么我们就需要通过通知中心将通知递交给用户,代码如下:

 //递交通知
 [[NSUserNotificationCenter defaultUserNotificationCenter] scheduleNotification:notification];
    //设置通知的代理
 [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];

另外NSUserNotificationCenter提供了三个代理来,让软件在通知不同状态下收到消息

//通知已经提交给通知中心
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didDeliverNotification:(NSUserNotification *)notification
{
    
}
//用户已经点击了通知
- (void)userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification
{
    
}

// Sent to the delegate when the Notification Center has decided not to present your notification, for example when your application is front most. If you want the notification to be displayed anyway, return YES.
//returen YES;强制显示(即不管通知是否过多)
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center shouldPresentNotification:(NSUserNotification *)notification
{
    return YES;
}

通知和iOS一样,也提供了删除通知的功能,代码如下:

//删除已经显示过的通知
[[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];


转载于:https://my.oschina.net/u/172362/blog/206771

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值