正如@rmaddy 在评论中提到的那样,这不能按照您要求的方式完成。
在这部分
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(_:constraint:)), name: UIResponder.keyboardWillShowNotification, object: nil)
您无法控制选择器的发送方式(以及使用什么参数)。
UIKit在它的私有实现内部做了这样的事情(让我们暂时忽略它的实现并不是真正的 Swift,这在这里并不重要):
NotificationCenter.default.post(name: NSNotification.Name(rawValue: UIResponder.keyboardWillShowNotification), object: uiwindow, userInfo: systemUserInfoForKeyboardShow)
这意味着选择器已经发送,并且无法向可选的 userInfo 添加额外的内容(如果.post(...)代码中确实发生了这种情况,您可以这样做,但这里不是这种情况)。
您需要另一种方法NSLayoutConstraint来访问键盘选择器显示/隐藏处理程序中的当前对象。也许它应该是你的一个属性ViewController,也许是你的某种状态,AppDelegate或者可能是完全不同的东西,不知道你的代码的其余部分是不可能的。
编辑:根据您添加的评论,我假设您有这样的事情:
class ViewController: UIViewController {
@IBOutlet var constraint: NSLayoutConstraint?
}
如果是这样,您可以简单地访问 VC 中选择器处理程序中的约束:
class ViewController: UIViewController {
@IBOutlet var constraint: NSLayoutConstraint?
@objc func keyboardWillShow(_ notification: NSNotification) {
//do something with the constraint
print(constraint)
}
}
还有一个专用的UIKeyboardWillChangeFrameNotification,也许它可以为您提供开箱即用的东西。在这里查看答案