【发布时间】:2021-06-19 03:22:36
【问题描述】:
我有一个聊天应用程序,可以在表格视图中显示消息。当我调用键盘时,我想要:
- 要滚动到底部的表格视图
- 我希望任何消息和键盘之间没有重叠。
@objc private func keyboardWillShow(notification: NSNotification) {
if let userInfo = notification.userInfo {
let keyBoardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue
let keyboardViewEndFrame = view.convert(keyBoardFrame!, from: view.window)
let keyboardHeight = keyboardViewEndFrame.height
tableView.scrollToBottom() { indexPath in
let rectofCell = self.tableView.rectForRow(at: indexPath)
let lastCellFrame = self.tableView.convert(rectofCell, from: self.view.window)
if lastCellFrame.origin.y + lastCellFrame.size.height > keyboardViewEndFrame.origin.y {
let overlap = lastCellFrame.origin.y + lastCellFrame.size.height - keyboardViewEndFrame.origin.y
self.tableView.frame.origin.y = -overlap
}
}
}
}
extension UITableView {
func scrollToBottom(animated: Bool = true, completion: ((IndexPath) -> Void)? = nil) {
let sections = self.numberOfSections
let rows = self.numberOfRows(inSection: sections - 1)
if (rows > 0){
let indexPath = IndexPath(row: rows - 1, section: sections - 1)
self.scrollToRow(at: indexPath, at: .bottom, animated: true)
completion?(indexPath)
}
}
}
rectOfCell 的值显示(0.0, 5305.333518981934, 375.0, 67.33333587646484) 和转换后的值(0.0, 9920.000185648601, 375.0, 67.33333587646484),并且表格视图从屏幕上消失。
如果最后一条消息与键盘的最终位置重叠,我只想向上移动表格视图。例如,当调用键盘时(表格视图已经在底部或不在底部时),如果键盘的外观没有覆盖消息(即,有只是一条消息)。
【问题讨论】:
-
与其向上移动表格视图,不如先将其高度减少键盘高度,然后将其滚动到底部?除非我遗漏了什么,否则这样看起来更简单。你不需要计算最后一个单元格的框架或任何类似的东西。
-
@Sweeper 谢谢。当我进行一些研究时,我还没有看到这种方法,但它似乎满足了我的所有要求。随时发布答案。
标签: ios swift uitableview uikeyboard