How do you create custom notifications in Swift 3?

前端 未结 13 733
自闭症患者
自闭症患者 2020-12-04 09:07

In Objective-C, a custom notification is just a plain NSString, but it\'s not obvious in the WWDC version of Swift 3 just what it should be.

13条回答
  •  情书的邮戳
    2020-12-04 09:25

    If you want this to work cleanly in a project that uses both Objective-C and Swift at the same time, I found it to be easier to create the notifications in Objective-C.

    Create an .m/.h file:

    //CustomNotifications.h
    #import 
    
    // Add all notifications here
    extern const NSNotificationName yourNotificationName;
    
    //CustomNotifications.m
    #import "CustomNotifications.h"
    
    // Add their string values here
    const NSNotificationName yourNotificationName = @"your_notification_as_string";
    

    In your MyProject-Bridging-Header.h (named after your project) to expose them to Swift.

    #import "CustomNotifications.h"
    

    Use your notifications in Objective-C like this:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yourMethod:) name:yourNotificationName:nil];
    

    And in Swift (5) like this:

    NotificationCenter.default.addObserver(self, selector: #selector(yourMethod(sender:)), name: .yourNotificationName, object: nil)
    

提交回复
热议问题