这是我添加观察者的功能
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)
}
我收到此错误
表达式类型不明确,没有更多上下文
答案 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
,因为UIResponder
是UIKit
而不是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);