NSNotfication.addObserver - 更新到当前的 Swift 语法?

Posted

技术标签:

【中文标题】NSNotfication.addObserver - 更新到当前的 Swift 语法?【英文标题】:NSNotfication.addObserver - Update to current Swift Syntax? 【发布时间】:2017-07-24 15:54:43 【问题描述】:

目前正在遵循教程,但是,某些语法已过时。基本上代码应该显示和隐藏用户键盘。我在使用addObserver 方法时遇到了一些语法错误,Swift 希望我改用密钥路径,但是,如果我使用自动“修复”,我会遇到更多错误。谁能帮我解决这个问题?谢谢!

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
    

我收到调试消息:"Incorrect argument labels in call(have _selector:name, expected _forKeyPath:options:context"

【问题讨论】:

你不要将观察者添加到NSNotification,你应该将它们添加到NotificationCenter.default Not NotificationCenter.default 在 Swift 3 中不再可用吗? 它仍然可用 你当然是对的。谢谢! 【参考方案1】:

你的函数有参数,当你在观察者中添加它时丢失了

你必须使用NotificationCenter.default.addObserver 而不是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) 

【讨论】:

太棒了!我不太清楚为什么,但我之前尝试过使用 NotificationCenter 并没有奏效。无论如何,谢谢!

以上是关于NSNotfication.addObserver - 更新到当前的 Swift 语法?的主要内容,如果未能解决你的问题,请参考以下文章