我有一个包含表单的视图控制器,我想获取文本字段的底部 Y 位置和键盘顶部 Y 位置之间的高度(距离(。 我做了一个说明我的意思: 插图 我尝试过但不起作用的代码:
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
}
我想实现的事情是在TextField
和Keyboard
之间画一个UIView
我得到的distanceHeight
值不正确,高度超过键盘。
感谢您的帮助。
如果keyboardWillShow
则设置keyboardHeight
= 0
,如果keyboardWillHide
则KeyboardWillChangeFrame
keyboardHeight
=keyboardFrameEnd.height
keyboardHeight
= 0
其余代码工作正常
假设您的文本字段是 self.view 的子视图
let textFieldBottomY = tfAny.frame.origin.y + tfAny.frame.size.height
let keyboardTopY = self.view.frame.height - keyboardHeight
let distanceHeight = abs(keyboardTopY - textFieldBottomY)
否则如果在滚动视图中
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)