我有一个包含表单的 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(self.keyboardWillShow), name: .UIKeyboardWillShow, object: nil) 调用
keyboardHeight
来自此函数:
if let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue {
let keyboardSize = keyboardFrame.cgRectValue.height
}
我想要实现的目标是在 TextField
和 Keyboard
之间绘制一个 UIView
distanceHeight 的值
我得到的不正确,高度超出了键盘。
感谢您的帮助。
最佳答案
设置键盘高度
= 0
如果keyboardWillShow
或KeyboardWillChangeFrame
keyboardHeight
= keyboardFrameEnd.height
否则如果keyboardWillHide
键盘高度
= 0
其余代码工作正常
假设你的textField是self.view的 subview
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)
关于ios - 获取 TextField 和键盘之间的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50896549/