ios - Swift-调整约束以允许键盘
问题描述
我是一名新的 SWIFT 程序员,将学习编码作为一种爱好。我即将完成我的第一个应用程序,并且有一个表格视图,其中单元格的一部分包含一个文本字段,用户可以在其中编辑其中包含的数据。
当用户在文本字段中单击时,键盘会弹出并遮住大部分 tableview。
我已经对此进行了研究,并且在过去的一个小时里一直在研究解决方案的领域,但我有点不知道从哪里开始。据我所知,我应该只调整 tableview 上的约束,使其从视图底部不是 0,而是键盘高度的像素数。
所以我理解这个概念,但不知道如何执行这两个主要部分:
- 我如何设置一个监听器,以便当键盘出现时我可以运行一些代码
- 如何以编程方式设置我的 tableview 的约束?
解决方案
您需要在 viewDidLoad 中附加一些观察者:
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange), name: UIResponder.keyboardWillHideNotification, object: nil)
记得在 viewWillDisappear 中移除它们:
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil)
您需要一个 @objc 函数供观察者调用:
@objc private func keyboardWillChange(_ notification: Notification) {
guard let userInfo = (notification as Notification).userInfo, let value = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else {
return
}
if ((userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue) != nil {
let isKeyboardShowing = notification.name == UIResponder.keyboardWillShowNotification
var newHeight: CGFloat
let textHeight = inputTextView.textContainer.size.height
if isKeyboardShowing {
newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
bottomConstraint.constant = newHeight + textHeight
view.bringSubviewToFront(messageInputContainerView)
UIView.animate(withDuration: 0, delay: 0,
options: .curveEaseOut,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
else {
view.bringSubviewToFront(messageInputContainerView)
newHeight = value.cgRectValue.height - view.safeAreaInsets.bottom
bottomConstraint?.constant = view.safeAreaInsets.bottom + messageInputContainerView.bounds.height - textHeight
UIView.animate(withDuration: 0,
delay: 0,
options: .curveEaseOut,
animations: { self.view.layoutIfNeeded() },
completion: nil)
}
}
}
bottomConstraint
在这种情况下,您的类引用是附加到情节提要上 tableView 的底部,并且是我们在键盘打开和关闭时可移动的基线。您将需要为自己的用例/大小调整值和约束选择。在这个例子messageInputContainerView
中是我们的容器。inputTextView
推荐阅读
- javascript - 用户上传音频以仅在客户端 javascript 上播放
- python - 使用 Python 根据数据集中的多个条件识别和删除异常值
- sql - 如何修复我的 postgres 函数语法以适应用户参数
- git - 如何在不解决其他提交冲突的情况下在 git 中变基,或者压缩我的所有提交,同时不影响其他人的提交?
- java - java中的回溯筷子
- docker - Angular 11 应用程序和 .NET core 3.1 在 Docker 中容器化
- php - PhpStorm 忽略符号链接的作曲家供应商库
- odoo - 如何在英语中使用相同单词但在其他语言中使用不同单词的情况下保持翻译分开?
- python - 如何在 MDI 区域中显示子窗口?
- prolog - 如何在序言中打印?