delegatesswiftdelegation

Delegates in swift?


How does one go about making a delegate, i.e. NSUserNotificationCenterDelegate in swift?


Solution

  • It is not that different from obj-c. First, you have to specify the protocol in your class declaration, like following:

    class MyClass: NSUserNotificationCenterDelegate
    

    The implementation will look like following:

    // NSUserNotificationCenterDelegate implementation
    func userNotificationCenter(center: NSUserNotificationCenter, didDeliverNotification notification: NSUserNotification) {
        //implementation
    }
    
    func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification) {
        //implementation
    }
    
    func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
        //implementation
        return true
    }
    

    Of course, you have to set the delegate. For example:

    NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self;