gpt4 book ai didi

ios - 从 UITableView 中删除项目后索引超出范围

转载 作者:可可西里 更新时间:2023-11-01 00:57:04 24 4
gpt4 key购买 nike

请帮我找出我的错误所在。我有一个 TableView ,数据源是一个名为 items 的数组。从项目数组中删除一项后,将调用 cellForRowAt 方法并且参数 indexPath.row 等于 items.count。只有当行数刚好足以让一项超出 TableView 的 View 时,才会发生这种情况。当它发生时,它会导致 fatal error (索引超出范围)。在这种情况下使用 hack 并降低 IndexPath.row 的值。

请看下图:

enter image description here

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)
}
}
}

如何重现:

  1. 向下滚动到 Y 是屏幕上的最后一项

enter image description here

  1. 尝试向左滑动删除Y

enter image description here

  1. 并得到以下错误

enter image description here

enter image description here

最佳答案

您的删除代码看起来不错,但您不应该执行您在 cellForRowAt 中执行的操作。改为这样做:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell
cell.set(items[indexPath.row])

return cell
}

你的 numberOfRowsInSection 应该是这样的:

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

更新:
我们刚刚确认这是与 Xcode 9 beta 和 iOS 11 相关的错误。在 Xcode 8.x 上工作正常。 OP 将提交 bug就此向 Apple。

关于ios - 从 UITableView 中删除项目后索引超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44635679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com