【问题标题】:How to prevent the last table cell from overlapping with the keyboard如何防止最后一个表格单元格与键盘重叠
【发布时间】:2021-06-19 03:22:36
【问题描述】:

我有一个聊天应用程序,可以在表格视图中显示消息。当我调用键盘时,我想要:

  1. 要滚动到底部的表格视图
  2. 我希望任何消息和键盘之间没有重叠。
@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


【解决方案1】:

你不需要为这样的事情管理tableView.frame。您只需要确保当键盘出现时,tableView 从底部添加必要的 contentInset 值,以便用户仍然可以在键盘仍在屏幕上的情况下看到 tableView 中的所有内容。

你只需要这个 -

// when keyboard appears
let insets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardHeight, right: 0)
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets

// when keyboard disappears
let insets: UIEdgeInsets = .zero
tableView.contentInset = insets
tableView.scrollIndicatorInsets = insets

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多