Crex
Crex 是一个用于简单和类型安全的 Notification Center 使用的库。通过代码自动完成,发布额外信息非常方便。
示例
要运行示例项目,请克隆仓库,然后首先从 Example 目录运行 pod install
要求
-
iOS 9.3+
-
Swift 4.1
安装
Crx 可通过 CocoaPods 获取。要安装它,只需将以下行添加到您的 Podfile 中
pod 'Crex'
用法
定义事件
import Crex
struct QueueStateChanged: CrexEvent {
typealias PayloadType = QueueStateChanged.Payload
static let notificationName = NSNotification.Name(rawValue: "MyApp.QueueStateChanged")
static let transformation: CrexTransformation = nil
struct Payload {
let updatedAt = Date()
let itemsLeft: Int
}
}
注册观察者
Crex<QueueStateChanged>.addObserver { (_, queueState) in
guard let queueState = queueState else {
return
}
print("Queue updated: \(queueState.updatedAt), items left: \(queueState.itemsLeft)")
}
发布事件
Crex<QueueStateChanged>.post(QueueStateChanged.Payload(itemsLeft: 42))
使用系统通知
struct ApplicationDidBecomeActive: CrexEvent {
typealias PayloadType = Void
static let notificationName: NSNotification.Name = .UIApplicationDidBecomeActive
static let transformation: CrexTransformation = nil
}
Crex<ApplicationDidBecomeActive>.addObserver { (_, _) in
print("Application did become active")
}
使用转换
有时只需从系统发送的通知中获取一些数据即可。此外,在这种方法中,我们在从userInfo字典获取数据时不会创建重复。
struct KeyboardWillShow: CrexEvent {
typealias PayloadType = KeyboardWillShow.KeyboardPayload
static let notificationName: NSNotification.Name = .UIKeyboardWillShow
static let transformation: CrexTransformation = { (userInfo: CrexUserInfo) in
guard let keyboardSize = userInfo[UIKeyboardFrameBeginUserInfoKey] as? CGRect,
let animationDuration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval else {
return nil
}
return KeyboardPayload(height: keyboardSize.height, animationDuration: animationDuration)
}
struct KeyboardPayload {
let height: CGFloat
let animationDuration: TimeInterval
}
}
Crex<KeyboardWillShow>.addObserver { (_, keyboard) in
guard let keyboard = keyboard else {
return
}
print("Will show keyboard height: \(keyboard.height), duration: \(keyboard.animationDuration)")
}
作者
Marek Rogowski, [email protected]
许可
Crex可在MIT许可下使用。更多信息请参阅LICENSE文件。