gpt4 book ai didi

ios - 获取 TextField 和键盘之间的高度

转载 作者:行者123 更新时间:2023-11-30 11:24:36 25 4
gpt4 key购买 nike

我有一个包含表单的 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
}

我想要实现的目标是在 TextFieldKeyboard 之间绘制一个 UIView distanceHeight 的值 我得到的不正确,高度超出了键盘。

感谢您的帮助。

最佳答案

设置键盘高度 = 0

如果keyboardWillShowKeyboardWillChangeFrame
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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com