我想获取设备的键盘高度以在相同高度构建一些对象。这些对象将在键盘实际出现之前就存在,因此我无法使用像 this 这样的方法。我想知道是否有一种方法可以在不实际出现键盘的情况下获取键盘的高度?
最佳答案
Iv也有类似的问题。我还没有找到一种方法来获取键盘高度而不首先显示键盘,但我确实有办法解决它。
var keyboardHeight = CGFloat()
var keyboardFirstTime = true
在 View 中确实加载了
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
给出键盘高度的单独函数
func keyboardWillShow(_ notification:Notification)
{
let userInfo:NSDictionary = (notification as NSNotification).userInfo! as NSDictionary
let keyboardFrame:NSValue = userInfo.value(forKey: UIKeyboardFrameEndUserInfoKey) as! NSValue
let keyboardRectangle = keyboardFrame.cgRectValue
keyboardHeight = keyboardRectangle.height
}
在textFieldDidBeginEditing
func textFieldDidBeginEditing(_ textField: UITextField)
{
//adds .01 delay to wait and assign keyboard height for the first time
if keyboardFirstTime == true
{
let when = DispatchTime.now() + 0.01
DispatchQueue.main.asyncAfter(deadline: when)
{
UIView.animate(withDuration: 0.25, delay: 0, options: [.curveEaseOut], animations:
{
self.searchField.frame.origin.y = self.view.frame.height - self.keyboardHeight - self.searchField.frame.size.height
}, completion: nil)
}
keyboardFirstTime = false
}
else
{
UIView.animate(withDuration: 0.3, delay: 0, options: [.curveEaseOut], animations:
{
self.searchField.frame.origin.y = self.view.frame.height - self.keyboardHeight - self.searchField.frame.size.height
}, completion: nil)
}
textField.text = ""
}
关于ios - 在键盘出现之前获取键盘高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40474580/