hex*_*mer 110 nsnotifications nsnotification nsnotificationcenter swift swift3
在Objective-C中,自定义通知只是一个简单的NSString,但在WWDC版本的Swift 3中它并不明显.
Ces*_*ela 369
有一种更清洁(我认为)的方式来实现它
extension Notification.Name {
static let onSelectedSkin = Notification.Name("on-selected-skin")
}
Run Code Online (Sandbox Code Playgroud)
然后你可以像这样使用它
NotificationCenter.default.post(name: .onSelectedSkin, object: selectedSkin)
Run Code Online (Sandbox Code Playgroud)
hex*_*mer 36
Notification.post定义为:
public func post(name aName: NSNotification.Name, object anObject: AnyObject?)
Run Code Online (Sandbox Code Playgroud)
在Objective-C中,通知名称是一个普通的NSString.在Swift中,它被定义为NSNotification.Name.
NSNotification.Name定义为:
public struct Name : RawRepresentable, Equatable, Hashable, Comparable {
public init(_ rawValue: String)
public init(rawValue: String)
}
Run Code Online (Sandbox Code Playgroud)
这有点奇怪,因为我希望它是一个Enum,而不是一些看似没有更多好处的自定义结构.
NSNotification.Name的通知中有一个typealias:
public typealias Name = NSNotification.Name
Run Code Online (Sandbox Code Playgroud)
令人困惑的部分是Swift中存在Notification和NSNotification
因此,为了定义您自己的自定义通知,请执行以下操作:
public class MyClass {
static let myNotification = Notification.Name("myNotification")
}
Run Code Online (Sandbox Code Playgroud)
然后叫它:
NotificationCenter.default().post(name: MyClass.myNotification, object: self)
Run Code Online (Sandbox Code Playgroud)
hal*_*l_g 31
您也可以使用协议
protocol NotificationName {
var name: Notification.Name { get }
}
extension RawRepresentable where RawValue == String, Self: NotificationName {
var name: Notification.Name {
get {
return Notification.Name(self.rawValue)
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后将通知名称定义为enum您想要的任何位置.例如:
class MyClass {
enum Notifications: String, NotificationName {
case myNotification
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它
NotificationCenter.default.post(name: Notifications.myNotification.name, object: nil)
Run Code Online (Sandbox Code Playgroud)
通过这种方式,通知名称将与基金会分离Notification.Name.并且您只需要修改您的协议,以防Notification.Name更改实施.
Zol*_*adi 13
更简单的方法:
let name:NSNotification.Name = NSNotification.Name("notificationName")
NotificationCenter.default.post(name: name, object: nil)
Run Code Online (Sandbox Code Playgroud)
efr*_*dze 10
您可以向NSNotification.Name添加自定义初始值设定项
extension NSNotification.Name {
enum Notifications: String {
case foo, bar
}
init(_ value: Notifications) {
self = NSNotification.Name(value.rawValue)
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
NotificationCenter.default.post(name: Notification.Name(.foo), object: nil)
Run Code Online (Sandbox Code Playgroud)
小智 8
我可能会建议另一个与@CesarVarela建议的选项类似的选项。
extension Notification.Name {
static var notificationName: Notification.Name {
return .init("notificationName")
}
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以轻松发布和订阅通知。
NotificationCenter.default.post(Notification(name: .notificationName))
Run Code Online (Sandbox Code Playgroud)
希望这会帮助你。
| 归档时间: |
|
| 查看次数: |
43894 次 |
| 最近记录: |