首页 > 解决方案 > 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 单元格是根据内容自行调整大小的,所以我不能只将行数乘以一个常数。)

提前感谢您提供有关如何执行此操作的任何建议。

标签: iosswiftautolayouttableview

解决方案


我想这会对你有所帮助。

  1. addKeyboardObserver()从您的方法调用viewWillAppear(_ animated: Bool)方法。
  2. 从你的调用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)
}

推荐阅读