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.
相关问题
- “Zero out” sensitive String data in Swift
- SwiftUI: UIImage (QRCode) does not load after call
- Get the NSRange for the visible text after scroll
- UIPanGestureRecognizer is not working in iOS 13
- What does a Firebase observer actually do?
相关文章
- Using if let syntax in switch statement
- Enum with associated value conforming to CaseItera
- Swift - hide pickerView after value selected
- Is there a Github markdown language identifier for
- How can I vertically align my status bar item text
- Adding TapGestureRecognizer to UILabel in Swift
- Attempt to present UIAlertController on View Contr
- Swift - Snapshotting a view that has not been rend
You could also use a protocol for this
And then define your notification names as an
enum
anywhere you want. For example:And use it like
This way the notification names will be decoupled from the Foundation
Notification.Name
. And you will only have to modify your protocol in case the implementation forNotification.Name
changes.@CesarVarela's answer is good, but to make the code slightly cleaner, you can do the following:
I may suggest another option which is similar to what @CesarVarela suggested.
This will let you post and subscribe on notifications easily.
Hope this will help you.
if you use string-only custom notifications, there's no reason to extend any classes but
String
Notification.post is defined as:
In Objective-C, the notification name is a plain NSString. In Swift, it's defined as NSNotification.Name.
NSNotification.Name is defined as:
This is kind of weird, since I would expect it to be an Enum, and not some custom struct with seemingly no more benefit.
There is a typealias in Notification for NSNotification.Name:
The confusing part is that both Notification and NSNotification exist in Swift
So in order to define your own custom notification, do somethine like:
Then to call it: