ios - IOS/Swift:确定表格视图最后填充行的垂直位置
问题描述
我在键盘出现和消失的屏幕上有一个表格视图。如果键盘将覆盖底部附近的行,我希望表格视图向上移动足以使行可见。
现在,当键盘出现时,我可以让整个 tableview 向上移动。这是有效的,因为 tableview 一直被限制在顶部和底部到边缘。
但是,如果顶部只有几行,当键盘出现并将 tableview 向上推时,这些行将不再可见。所以我想我需要通过底行和表格视图底部之间的距离来抵消表格视图的移动。
我可以使用以下代码获取键盘的高度:
var heightKeyboard : CGFloat?
func keyboardShown(notification: NSNotification) {
if let infoKey = notification.userInfo?[UIKeyboardFrameEndUserInfoKey],
let rawFrame = (infoKey as AnyObject).cgRectValue {
let keyboardFrame = view.convert(rawFrame, from: nil)
self.heightKeyboard = keyboardFrame.size.height
// Now is stored in your heightKeyboard variable
}
}
但是,我不知道如何获取 tableview 的最底部填充行的坐标。(tableview 单元格是根据内容自行调整大小的,所以我不能只将行数乘以一个常数。)
提前感谢您提供有关如何执行此操作的任何建议。
解决方案
我想这会对你有所帮助。
addKeyboardObserver()
从您的方法调用viewWillAppear(_ animated: Bool)
方法。- 从你的调用
NotificationCenter.removeObserver(self)
方法viewWillDisappear(_ animated: Bool)
。
`
func addKeyboardObserver() {
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: .UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: .UIKeyboardWillHide, object: nil)
}
@objc func keyboardWillShow(_ notification: NSNotification){
if let userInfo = notification.userInfo {
if let keyboardSize = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect {
guard let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double else {return}
tableView.contentInset = UIEdgeInsetsMake(0, 0, keyboardSize.height + padding, 0)
}
}
}
@objc func keyboardWillHide(_ notification: NSNotification){
guard let duration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? Double else {return}
tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
}
推荐阅读
- c# - 表格未附加 ajax 数据,而是在浏览器中显示 json 数组
- jsf - Primefaces 避免提交多个表单
- javascript - 限制 CSS 网格中的行数
- android - 在 API 28 但不是 API 24 的 AVD 上运行的应用程序
- c# - 在动态生成的下拉列表中触发更改事件
- postgresql - PostgreSQL 插入 2 个表?
- swift - 在swift中以默认情况访问switch case参数
- android - 向 AWS 用户池验证社交身份联合用户?- 安卓
- database - Wordpress 迁移问题 503 错误
- angular - 在 JHipster 中创建实体后重定向到路由