Search code examples
iosswiftxcodeparse-platform

NSNotfication.addObserver - Update to current Swift Syntax?


Currently following a tutorial, however, some of the syntax is outdated. Basically the code should show and hide the user keyboard. I get some syntax errors with the addObserver method and Swift wants me to use key path instead, however, if i use the auto 'fix-it' i get even more errors. Can anyone help me out with this? Thanks!

NSNotification.addObserver(self, selector: #selector(keyboardwillShow), name: .UIKeyboardWillShow, nil)       
NSNotification.addObserver(self, selector: #selector(keyboardwillHide), name: .UIKeyboardWillHide, nil)


func keyboardwillShow(_notification:NSNotification) {    
    keyboard = (_notification.userInfo![UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue
    UIView.animate(withDuration: 0.4) { 
        self.scrolledView.frame.size.height = self.scrollViewHeight - self.keyboard.height
    }
}

func keyboardwillHide(_notification:NSNotification) {
    UIView.animate(withDuration: 0.5) { 
        self.scrolledView.frame.size.height = self.view.frame.height
    }
}

I get the debug message: "Incorrect argument labels in call(have _selector:name, expected _forKeyPath:options:context"


Solution

  • Your function has argument, That is missing when you add it in observer

    And you have to use NotificationCenter.default.addObserver not NotificationCenter.addObserver

    let selectorForKeyBoardWillShow: Selector = #selector(ViewController.keyboardWillShow(_:))
    let selectorForKeyBoardWillHide: Selector = #selector(ViewController.keyboardWillHide(_:))
    
        // MARK: - Functions
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: selectorForKeyBoardWillShow, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: selectorForKeyBoardWillHide, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }
    
    
    // MARK: Keyboard Observer
    func keyboardWillShow(_ notification: Notification) {
    }
    
    func keyboardWillHide(_ notification: Notification) {
    }