【转载】User notification 的实现方法

原帖请看:http://cocoathings.blogspot.com/2013/01/introduction-to-user-notifications-in.html

 

想要实现如图这样的notification popup

弹出notification的代码如下

NSUserNotification *notification = [[NSUserNotification alloc] init];
notification.title = @"Hello, World!";
notification.informativeText = [NSString stringWithFormat:@"details details details"];
notification.soundName = NSUserNotificationDefaultSoundName;
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:notification];

但是这个popup并不是默认显示的,想要让他show出来还必须在程序里实现下面的方法:

- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
     shouldPresentNotification:(NSUserNotification *)notification
{
    return YES;
}

然后把NSUserNotificationCenter.的delegate设置为自己的程序,一般在主程序AppDelegate.m中实现即可(上面那个函数也在这个文件里)

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}

需要注意的是,想要成功设置delegate还必须让AppDelegate支持NSUserNotificationCenterDelegate 协议,即在它的头文件里加上这个协议即可。

然后运行程序就OK了。

 

posted @ 2014-12-22 16:25  裸奔的小鸟  阅读(303)  评论(0编辑  收藏  举报