在键盘高度出现之前获得它

时间:2016-11-07 21:03:54

标签: ios swift keyboard

我想让设备的键盘高度在同一高度构建一些对象。在键盘实际出现之前,这些对象将存在,因此我无法使用this之类的方法。我想知道是否有办法获得键盘的高度而不实际出现?

2 个答案:

答案 0 :(得分:0)

Iv也有类似的问题。我没有找到一种方法来获得键盘高度,而不是首先出现键盘,但我确实有办法解决它。

var keyboardHeight = CGFloat()
var keyboardFirstTime = true

在视图中加载了

 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 = ""
}

答案 1 :(得分:0)

一种方法是在某个地方创建一个textField,然后在viewDidLoad中使该textField首先成为响应者,然后立即将其隐藏。这只会在viewLoads发生一次。