【发布时间】:2017-09-16 08:30:24
【问题描述】:
请帮我找出我的错误。我有一个表格视图,数据源是一个称为项目的数组。从 items 数组中删除一项后,调用 cellForRowAt 方法并且参数 indexPath.row 与 items.count 相等。仅当行数刚好足以使一个项目超出表视图的视图时才会发生这种情况。 当它发生时,它会导致致命错误(索引超出范围)。在这种情况下使用 hack 并减少 IndexPath.row 的值。
请看下图:
cellForRowAt 的以下代码:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell
var i = indexPath.row
if i >= items.count { i = items.count - 1 } //XXX: hack! Sometimes called with indexPath.row is equal with items.count :(
cell.set(items[i])
return cell
}
删除的代码如下:
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if (editingStyle == UITableViewCellEditingStyle.delete)
{
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
}
}
我认为不相关,但我使用的是 iOS 11.0
更新
我试过了,下面很简单的代码也受影响:
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
var items = ["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
override func viewDidLoad()
{
super.viewDidLoad()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath)
cell.textLabel?.text = "\(items[indexPath.row])"
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
if (editingStyle == UITableViewCellEditingStyle.delete)
{
items.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
}
}
}
如何重现:
- 向下滚动到 Y 是屏幕上的最后一项
- Y向左滑动尝试删除
- 并出现以下错误
【问题讨论】:
-
您在
cellForRowAt中的“黑客”不应该存在。如果你真的需要它,那么你的numberOfRowsInSection就有问题。 -
我的 numberOfRowsInSection 返回:return items.count
-
在删除行(
items中的索引项)后尝试重新加载 tableVewtableView.reloadData(),以便从新的 items.count 更新 numberOfRowsInSection -
我在发布之前尝试过,但遇到了同样的错误。 :(但是谢谢!
标签: ios swift uitableview delete-row