我想在键盘显示时更改视图的框架

时间:2018-09-17 13:02:54

标签: ios swift swift4.2

这是我添加观察者的功能

func subscribeToKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)
}

但是.UIKeyboardWillShow给我一个错误

  

'UIKeyboardWillShow'已重命名为   'UIResponder.keyboardWillShowNotification'

     

将“ UIKeyboardWillShow”替换为   'UIResponder.keyboardWillShowNotification'

但是当我更换它

func subscribeToKeyboardNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIResponder.keyboardWillShowNotification, object: nil)
}

我收到此错误

  

表达式类型不明确,没有更多上下文

4 个答案:

答案 0 :(得分:3)

不带点

NotificationCenter.default.addObserver(self, 
selector: #selector(keyboardWillShow), 
name: UIResponder.keyboardWillShowNotification, object: nil)

答案 1 :(得分:0)

let notificationCenter = NotificationCenter.default

notificationCenter.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: nil) { (notification) in
                self.keyboardWillShow(notification: notification)
            }
notificationCenter.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: nil) { (notification) in
                self.keyboardWillHide(notification: notification)
            }

答案 2 :(得分:0)

只需导入模块UIKit,因为UIResponderUIKit而不是Foundation模块的一部分

  

SWIFT 5代码

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addObservers()
    }

    public func addObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(handleKeyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
    }

    @objc func handleKeyboardWillShow(_: Notification) {
        // Here handle keyboard
    }
}

答案 3 :(得分:-1)

我已经使用了它,并且工作得很好

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShowOrHide(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil);
相关问题