首页 > 解决方案 > 为表格视图的高度分配上限?

问题描述

我有一个高度动态调整的表格视图。调整高度,使 tableview 只包含一定数量的行,并且没有空行。因此,如果只有 2 行,则高度较小,如果有 4 行,则高度较大。但是,我不希望它的高度超过某个点。如何允许动态调整高度,同时不让高度超过某个点?

这是我的代码:

@IBOutlet var tableView: UITableView!

@IBOutlet var tableViewHeightConstraint: NSLayoutConstraint!

var items: [String] = ["Swift", "Is", "So", "Amazing"]

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "Cell") as! UITableViewCell

    // Make sure the table view cell separator spans the whole width
    cell.preservesSuperviewLayoutMargins = false
    cell.separatorInset = UIEdgeInsets.zero
    cell.layoutMargins = UIEdgeInsets.zero

    cell.textLabel?.text = self.items[indexPath.row]

    return cell
}

override func viewWillAppear(_ animated: Bool) {
    // Adjust the height of the tableview
    tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: tableView.contentSize.height)

    // Add a border to the tableView
    tableView.layer.borderWidth = 1
    tableView.layer.borderColor = UIColor.black.cgColor
    print("We ran ViewWillAppear")
}

// This function is used for adjusting the height of the tableview
override func viewDidLayoutSubviews(){
    tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: tableView.contentSize.height)
    tableView.reloadData()
}

// Allow cell deletion in tableview
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

    let delete = UITableViewRowAction(style: .destructive, title: "Delete") { (action, indexPath) in
        // delete item at indexPath
        self.items.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
        self.tableViewHeightConstraint.constant = self.tableView.contentSize.height - 44
        print(self.items)
        print("Number of rows: \(tableView.numberOfRows(inSection: 0))")
    }

    delete.backgroundColor = UIColor.blue
    return [delete]
}

标签: iosswiftuitableviewtableview

解决方案


viewWillAppear,你可以试试

let limit:CGFloat = 900.0

if tableView.contentSize.height  < limit {
    tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: tableView.contentSize.height)
}
else {
    tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: limit )
}

或将值设置为

tableViewHeightConstraint.constant = ( tableView.contentSize.height < limit ) ? tableView.contentSize.height : limit

self.view.layoutIfNeeded()

推荐阅读