作者:羽星快乐_914_137 | 来源:互联网 | 2023-01-13 12:56
我正在尝试使用iOS 11方式在表格视图行中添加滑动操作。我想添加一个删除行的操作。
我的测试表视图显示从0到9的数字,数据源是一个简单的整数数组,称为numbers
:
class ViewController: UIViewController {
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
选择一行时,我将打印以下相关值numbers
:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(numbers[indexPath.row])
tableView.deselectRow(at: indexPath, animated: true)
}
我实现新的委托trailingSwipeActionsConfigurationForRowAt
,如下所示:
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .destructive, title: "Delete") { (_, _, completionHandler) in
self.numbers.remove(at: indexPath.row)
completionHandler(true)
}
return UISwipeActionsConfiguration(actions: [delete])
}
当我在行上滑动时,删除工作正常。但是,这就是我的问题,当我在删除后选择另一行时,关联的IndexPath错误...
例:
我选择第一行,打印的值为0:确定。
我删除第一行。
我选择新的第一行,输出的值为2,因为传入的IndexPath参数是行1,而不是行0:不好。
我做错了什么?
1> Murray Sagal..:
It is important to remember that there's a model, the numbers
array in your case, and a view, the cells that are displayed. When you remove the element from numbers
you are only updating the model.
In most cases, as you have it coded, you would get an error shortly thereafter because the model is out of sync with the view.
However, my testing indicates that when the style is .destructive
and you pass true
to completionHandler
Apple is sort of removing the row for you. Which is why you are seeing the row disappear. But there's something not quite right about it and I can't find any documentation on it.
In the meantime, just do this:
self.numbers.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
completionHandler(true)
And always remember that if you change with the model you need to update the view.