ios - 如何正确确定 iOS 上的键盘和文本字段位置?
问题描述
当键盘显示并且文本字段变得不可见时,我想提升视图。这是我的代码:
@objc func keyboardWillShow(notification: NSNotification) {
if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
let tfPos = lastTextField!.convert(lastTextField!.frame, to: self.view)
let tfBottom = tfPos.origin.y
let kbTop = keyboardSize.origin.y
if kbTop < tfBottom {
self.verticalCenterConstraint.constant = -(tfBottom - kbTop)
}
}
}
我确定键盘的顶部,然后是文本字段的底部。但是,文本字段的位置不正确,即使我可以在屏幕上清楚地看到它在键盘上方,但我的代码说它在 35pt 下方。我该如何解决?
解决方案
步骤 :- 1 为隐藏和显示通知添加观察者
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard),
name: Notification.Name.UIKeyboardWillHide, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard),
name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
步骤:- 2 实施目标方法
@objc func adjustForKeyboard(notification: Notification) {
let userInfo = notification.userInfo!
let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
if notification.name == Notification.Name.UIKeyboardWillHide {
yourTextView.contentInset = UIEdgeInsets.zero
} else {
yourTextView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: keyboardViewEndFrame.height, right: 0)
}
yourTextView.scrollIndicatorInsets = yourTextView.contentInset
let selectedRange = yourTextView.selectedRange
yourTextView.scrollRangeToVisible(selectedRange)
}
推荐阅读
- wpf - WPF ItemList ItemTemplate 边框问题
- python - 无类型下落不明
- javascript - 如何通过使用alpine js单击一个复选框来选中和取消选中所有复选框
- python - 列表乘法列表与列表
- cmake - CMake 不会为 IMPORTED_IMPLIB 生成规则
- javascript - 如何在特定事件中自定义电子边框?
- mysql - 如果列大于某个值,则更新列
- angular - 使用 ag-grid,每当相邻单元格的 cellValueChanged 事件触发时,如何设置单元格的值?
- javascript - 从父组件 React 渲染 HTML
- c++ - 带有三个参数的 typedef 是什么意思?