获取TextField和Keyboard之间的高度

时间:2018-06-17 12:18:04

标签: ios iphone swift

我有一个包含表单的ViewController,我想得到TextField的底部Y位置和键盘顶部Y位置之间的高度(距离)。 我举例说明了我的意思: Illustration 我尝试过的代码但没有奏效:

let textFieldBottomY = myTextField.frame.origin.y + myTextField.frame.size.height
let keyboardTopY = self.view.frame.height - keyboardHeight

distanceHeight = keyboardTopY - textFieldBottomY

NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: .UIKeyboardWillShow, object: nil)调用上述函数 keyboardHeight来自此功能:

if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
        let keyboardSize = keyboardFrame.cgRectValue.height
}

我想要实现的是在UIViewTextField之间绘制Keyboard我得到的distanceHeight的值不正确且高度超过了键盘。

感谢帮助。

1 个答案:

答案 0 :(得分:0)

设置keyboardHeight = 0

如果keyboardWillShowKeyboardWillChangeFrame
keyboardHeight = keyboardFrameEnd.height
否则如果keyboardWillHide
keyboardHeight = 0

其余的代码工作正常 假设您的textField是self.view的子视图

let textFieldBottomY = tfAny.frame.origin.y + tfAny.frame.size.height
let keyboardTopY = self.view.frame.height - keyboardHeight    
let distanceHeight = abs(keyboardTopY - textFieldBottomY)

如果在scrollView中

let textFieldBottomPoint = CGPoint(x: 0, y: tfAny.frame.origin.y + tfAny.frame.height)
let textFieldBottomY = scrollView.convert(textFieldBottomPoint, to: view).y
let keyboardTopY = self.view.frame.height - keyboardHeight
let distanceHeight = abs(keyboardTopY - textFieldBottomY)