我一直在努力将键盘的高度设置为Swift 4.2。当键盘显示接受通知作为参数的键盘时,我一直在使用通知中心来调用函数,我认为这很标准吗?在这里我要计算高度。但是,通知对象缺少数据,我无法计算高度。
NSConcreteNotification 0x16e43a710 {
name = UIKeyboardDidShowNotification; userInfo = {
UIKeyboardAnimationCurveUserInfoKey = 7;
UIKeyboardAnimationDurationUserInfoKey = "0.25";
UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {0, 0}}";
UIKeyboardCenterBeginUserInfoKey = "NSPoint: {0, 0}";
UIKeyboardCenterEndUserInfoKey = "NSPoint: {0, 0}";
UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 0}, {0, 0}}";
UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 0}, {0, 0}}";
UIKeyboardIsLocalUserInfoKey = 1;
}
}
我从自己的init方法调用commonInit函数,该函数设置了要调用的方法:
private func commonInit() {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(notification:)), name: UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)
}
KeyboardWillShow函数
@objc private func keyboardWillShow(notification:NSNotification) {
let userInfo = notification.userInfo! as NSDictionary
let keyboardFrame = userInfo.value(forKey: UIResponder.keyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
let keyboardHeight = keyboardRectangle.height
print(keyboardHeight)
}
是否缺少一些东西来获取通知数据?
答案 0 :(得分:-1)
这就是我经常使用的:
func addObservers() {
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification,
object: nil,
queue: nil) { [weak self] (notification) in
self?.keyboardWillShow(notification: notification as NSNotification)
}
NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification,
object: nil,
queue: nil) { [weak self] (notification) in
self?.keyboardWillHide(notification: notification as NSNotification)
}
}
func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
let keyboardHeight = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue.size.height
}
//... do your stuff...
}