我在notifications
中有多个View Controller
,并希望将他们的名字保存在Enum
中:
enum KeyboardNotifications : Notification.Name{
case didAppear = Notification.Name(rawValue:"cfisher.keyboardDidAppear")
}
不幸的是,这不起作用,我收到编译错误:raw value for enum case must be a literal value
。
到底有没有?
我正在使用Swift 3,BTW
答案 0 :(得分:3)
这样,
enum Notes: String {
case note1 = "note1"
case note2 = "note2"
var notification : Notification.Name {
return Notification.Name(rawValue: self.rawValue )
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.post(name: Notes.note2.notification ,object: nil, userInfo: nil)
}
}
答案 1 :(得分:0)
解决方法是将通知存储在struct
中。
为了便于阅读/清除代码,您可以使用全局func
发布通知。
struct KeyboardNotifications {
static let didAppear = "cfisher.keyboardDidAppear"
static let didSomethingElse = "cfisher.keyboardDidSomethingElse"
}
func postNotification(_ aName: String,
object anObject: Any?,
userInfo aUserInfo: [AnyHashable : Any]? = nil) {
NotificationCenter.default.post(name: Notification.Name(rawValue: aName),
object: anObject,
userInfo:aUserInfo)
}
发布通知将如下所示:
postNotification(KeyboardNotifications.didAppear, object: nil)
此解决方案假设您只发布到默认NotificationCenter
。