Reputation: 26
While trying to use the new Swift NotificationCenter, I am trying to create observer objects as properties (against the classic Obj-C pattern of assigning observers to self):
private let keyboardWillShowObserver = {
return NotificationCenter.default.addObserver(forName: .UIKeyboardWillShow, object: nil, queue: nil, using: self.keyboardWillShow(_:))
}()
private func keyboardWillShow(_ notification: Notification) {
bottomVerticalSpaceConstraint.constant = 400
}
The problem is that I get the following error message, even though I have the member function part of the same class:
Value of type '(NSObject) -> () -> MyAwesomeViewController' has no member 'keyboardWillShow'
Upvotes: 0
Views: 801
Reputation: 1469
Since your keyboardWillShowObserver
is not lazy, it's closure will be executed during instance initialization of MyAwesomeViewController
. As far as I understand, that means self
will be interpreted as MyAwesomeViewController
class but not the instance of class.
There is an easy way to fix this error: make private lazy var keyboardWillShowObserver
so the closure will be executed on instance after it will be completely initialized.
Upvotes: 1
Reputation: 6067
HomeViewController is your viewController
private let keyboardWillShowObserver = {
return NotificationCenter.default.addObserver(forName: .UIKeyboardWillShow, object: nil, queue: nil, using: { (Notification) in
HomeViewController.keyboardWillShow (Notification)
})
}()
static func keyboardWillShow(_ notification: Notification) {
// bottomVerticalSpaceConstraint.constant = 400
}
Upvotes: 1