首页 > 解决方案 > 键盘消失时增加Tableview的高度?

问题描述

每当键盘消失时,我想增加表格视图的高度。我有一个从底部向上填充的表格视图。tableview 没有完全填充数据,这意味着 tableview 顶部有一些空白空间。表格视图中会有一些单元格。由于表格视图是从底部向上填充的,因此这些单元格应该朝向表格视图的底部。当显示键盘时,tableview 的总高度大约是屏幕的一半。当键盘消失时,tableview 的总高度应该几乎是整个屏幕。这意味着当键盘消失时,单元格应从屏幕下方开始。

这是当 tableview 中有两个单元格时的样子:

在此处输入图像描述

这是向 tableview 添加另外两个单元格时的样子:

在此处输入图像描述

这是键盘消失时的样子:

在此处输入图像描述

当键盘消失时,四个单元格应该从屏幕底部开始,而不是从屏幕中间开始。四个单元格应该向下移动,以便它们从屏幕底部的灰线开始。第一个单元格(显示“Apple”)的位置与屏幕底部的灰线位置之间不应有很大的差距。同时,tableView 本身应该更大。这意味着虽然 tableview 的顶部保持在同一个位置,但 tableview 的底部现在比以前低了,因为键盘现在没有占据大约一半的屏幕。我怎样才能做到这一点?谢谢。

这是我现在的代码:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var lowerGrayLine: UIView!

    @IBOutlet weak var tableView: UITableView!

    var fruits = [FruitModel]()

    override func viewDidLoad() {
        super.viewDidLoad()

        //Adjust height of the lower Gray Line
        lowerGrayLine.frame.origin.y = 411

        //No dividing lines in the tableview initially
        self.tableView.separatorStyle = .none

        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 140

        if (self.tableView(self.tableView, numberOfRowsInSection: 0) > 0) 
        {
            self.updateTableContentInset()
        }

        // Allow for keyboard dismissal
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(ViewController.dismissKeyboard))
        view.addGestureRecognizer(tap)

        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

        // Show keyboard
        textField.becomeFirstResponder()
    }

    func keyboardWillShow(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            //Adjust text box, and dividing line placement
            textField.frame.origin.y = 416
            lowerGrayLine.frame.origin.y = 411
        }
    }

    func keyboardWillHide(notification: NSNotification) {
        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
            textField.frame.origin.y = 597
            lowerGrayLine.frame.origin.y = 557
        }
    }

    //Calls this function when the tap is recognized.
    func dismissKeyboard() {
        //Causes the view (or one of its embedded text fields) to resign the first responder status.
        view.endEditing(true)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.fruits.count;
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "fruitCell"
        guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? FruitTableViewCell else {
            fatalError("The dequeued cell is not an instance of FruitTableViewCell.")
        }

        var fruitName = fruits[indexPath.row]
        var fruitNamename = fruitName.name

        var colon = ":"

        cell.nameLabel.text = fruitNamename + colon

        cell.fruitLabel.text = fruitName.fruit

        //Make some adjustments to make a line appear when a fruitCell is actually being shown
        cell.preservesSuperviewLayoutMargins = false
        cell.separatorInset = UIEdgeInsets.zero
        cell.layoutMargins = UIEdgeInsets.zero

        // This causes the bottom-most cell to not have a cell separator 
        if (indexPath.row == fruits.count-1) {
            cell.separatorInset = UIEdgeInsetsMake(0, cell.bounds.size.width, 0, 0);
        }
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }

    // Adjust the tableView
    func updateTableContentInset() {
        let numRows = tableView(tableView, numberOfRowsInSection: 0)

        var contentInsetTop = tableView.bounds.size.height
        for i in 0..<numRows {
            contentInsetTop -= tableView(tableView, heightForRowAt: IndexPath(item: i, section: 0))
            if contentInsetTop <= 0 {
                contentInsetTop = 0
            }
        }
        self.tableView.contentInset = UIEdgeInsetsMake(contentInsetTop, 0, 0, 0)
        self.tableView.scrollToRow(at: IndexPath(item: numRows-1, section: 0), at: .bottom, animated: false)
        //Prevent scrolling
        self.tableView.bounces = false;
        //When we have actual fruit Cells to show, we want the line divisions
        self.tableView.separatorStyle = .singleLine
    }
}

我尝试将以下代码添加到我的 keyboardWillShow 函数中:

var tableViewFrame: CGRect!
tableViewFrame = self.tableView.frame
tableViewFrame.size.height += 146.0
tableView.frame = tableViewFrame
tableView.contentInset = UIEdgeInsetsMake(146.0, 0, 0, 0);

但是,当键盘消失时,屏幕上会出现水平灰线,如下图:

编辑:

在此处输入图像描述

这些水平灰线(共六条)不应该存在。当键盘消失时,如何防止它们出现?

标签: iosswiftuitableviewtableview

解决方案


最简单的解决方案是IQKeyboardManager。这将为您管理键盘下方的空间。

否则,将底部约束添加tableViewBottomConstraint到表视图。设置其初始值tableViewBottomConstraint.constant = 0

现在设置它等于键盘高度+填充keyboardWillShow keyboardWillHide

func keyboardWillShow(notification: NSNotification) {
    tableViewBottomConstraint.constant = keyboardHeight + padding
    layoutTableView()
}

func keyboardWillHide(notification: NSNotification) {
    tableViewBottomConstraint.constant = 0
    layoutTableView()
}

private func layoutTableView() {
    UIView.animate(withDuration: 0.3, animations: {
        tableView.superview?.layoutIfNeeded()
    }, completion: nil) 
}

推荐阅读