我有一个包含表单的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
}
我想要实现的是在UIView
和TextField
之间绘制Keyboard
我得到的distanceHeight
的值不正确且高度超过了键盘。
感谢帮助。
答案 0 :(得分:0)
设置keyboardHeight
= 0
如果keyboardWillShow
或KeyboardWillChangeFrame
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)