個人第一個Mac開發筆記(NSUserNotification)

首先,咱們應該怎樣去建立一個通知中心呢?下面我以代碼的形式來展現如何構建一個通知中心:
app

 NSUserNotification *notification = [[NSUserNotification alloc] init];//建立通知中心
  notification.title = @"通知中心";
  notification.subtitle = @"小標題";
  notification.informativeText = @"詳細文字說明";
  notification.contentImage = [NSImage imageNamed:@"ladybugThumb.jpg"];
  
  //只有當用戶設置爲提示模式時,纔會顯示按鈕
  notification.hasActionButton = YES;
  notification.actionButtonTitle = @"肯定";
  notification.otherButtonTitle = @"取消";

 一條通知被建立好了,要讓該條通知顯示給用戶,那麼咱們就須要經過通知中心將通知遞交給用戶,代碼以下:ide

 //遞交通知
 [[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同樣,也提供了刪除通知的功能,代碼以下:code

//刪除已經顯示過的通知
[[NSUserNotificationCenter defaultUserNotificationCenter] removeAllDeliveredNotifications];
相關文章
相關標籤/搜索