【发布时间】:2018-11-23 15:10:39
【问题描述】:
我一直致力于在 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)
}
是否缺少获取通知数据的内容?
【问题讨论】:
-
您是在模拟器还是实际设备中尝试?如果您在模拟器中尝试,请按 Command+K 打开键盘。键盘出现了吗?
-
我在模拟器和设备上都试过了。键盘出现在屏幕上,但我没有获得足够的通知数据来计算高度。通知对象每次都是一样的
-
只计算键盘高度?