尝试在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)
答案 0 :(得分:4)
defaultCenter
是类方法(在Swift中也称为类型方法),因此它是
NSNotificationCenter.defaultCenter()
而不是
NSNotificationCenter().defaultCenter()
会在对象上调用实例方法 defaultCenter()
由NSNotificationCenter()
创建并返回。