我正在尝试删除tableview中的一行。删除行后,应该调整表视图,以使表视图中没有空白行。这是删除任何行之前的样子:
这是要删除行时的样子:
这是删除行后的样子:
删除第四行之后,不应有多余的空白行。我如何摆脱这一额外的行?
这是我目前的代码。如您所见,tableview的大小是动态调整的。根据是否有4个项目(如第一个图像所示)或是否有6个项目,表视图的总体大小是不同的。在这两种情况下,在发生任何删除之前,表中都没有多余的行(因此,在第一种情况下总共只有4行,在第二种情况下总共只有6行)。此外,该按钮应该位于表格视图末尾下方80像素处。删除一行后,该按钮将正确移动,如您所见,该按钮已从图像2移到了3。但是,看起来表格视图中仍然有一个额外的行。
@IBOutlet var tableView: UITableView!
@IBOutlet var newButton: UIButton!
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
}
// 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()
//Get the current height of the tableview
var tableViewHeight = self.tableView.contentSize.height
var tableViewEnding = 134 + tableViewHeight
var buttonPlacement = tableViewEnding + 80
// The New Button is 80 points below the ending of the tableView
newButton.frame.origin.y = buttonPlacement
print("Table View Height: \(tableViewHeight)")
}
// 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.viewDidLayoutSubviews()
print(self.items)
print("Number of rows: \(tableView.numberOfRows(inSection: 0))")
}
delete.backgroundColor = UIColor.blue
return [delete]
}
最佳答案
只需在视图中添加以下内容即可加载方法
tableView.tableFooterView = UIView()
现在将没有多余的空行。
下一步是
将高度约束添加到表视图并采用IBOutlet。
在对tableview进行任何更新之后,使用tableview的
contentSize.height
设置约束的常量值注意:如果您的单元格有繁重的工作要做,那么在重新加载数据旁边设置常量可能无法正常工作,在这种情况下,您可以尝试使用viewDidLayoutSubviews方法
希望对您有所帮助
关于ios - 删除行以进行动态调整的表格 View ?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50378673/