NSNotificationcenter没有成员名称' defaultCenter"错误-Swift

时间:2014-09-17 20:16:44

标签: ios cocoa-touch swift

尝试在swift中添加键盘观察器并获取错误

NSNotificationcenter does not have a member names 'defaultCenter"

使用

NSNotificationCenter().defaultCenter().addObserver(self, selector: Selector("keyboardWillAppear"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter().defaultCenter().addObserver(self, selector: Selector("keyboardWillHide"), name: UIKeyboardWillHideNotification, object: nil)

根据以下建议 NSNotificationCenter addObserver in Swift Swift: Keyboard Observer via NSNotificationCenter doesn't work

如果我删除defaultCenter我没有收到错误,但也没有观察键盘

NSNotificationCenter().addObserver(self, selector: Selector("keyboardWillAppear"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter().addObserver(self, selector: Selector("keyboardWillHide"), name: UIKeyboardWillHideNotification, object: nil)

1 个答案:

答案 0 :(得分:4)

defaultCenter类方法(在Swift中也称为类型方法),因此它是

NSNotificationCenter.defaultCenter()

而不是

NSNotificationCenter().defaultCenter()

会在对象上调用实例方法 defaultCenter()NSNotificationCenter()创建并返回。