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

标签 ios swift xcode parse-platform

目前正在学习教程,但是,某些语法已过时。基本上代码应该显示和隐藏用户键盘。我在 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
    }
}

我收到调试消息:“调用中的参数标签不正确(有 _selector:name,需要 _forKeyPath:options:context”

最佳答案

你的函数有参数,当你在观察者中添加它时缺少参数

而且你必须使用 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) {
}

关于ios - NSNotfication.addObserver - 更新到当前的 Swift 语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45285054/

相关文章:

ios - 尝试更改 UIAlertController 的消息颜色时应用程序崩溃,swift

ios - 适用于iOS应用的GCM(Google云消息传递)

ios - 无效目录 Users/node_modules/crypto-browserify react native

ios - UITableView 单元格在高度变化后显示错误的内容

ios - 启动时传递参数的 xcode 命令行测试

ios - 测试飞行 - 本地网络权限,TestFlight 构建中出现 NSBonjourServices 错误

ios - Swift - Firebase Auth with Microsoft Graph(重定向 URL 问题)

ios - 如何将以编程方式创建的 View Controller 的 View 设置为 SKYView?

ios - UIRefreshController 结束动画问题

xcode - 无法将 nsnumber 类型的值分配给值类型字符串