t_b*_*bzk 2 iphone xcode ios swift ios11
我正在尝试使用iOS 11方式在表格视图行中添加滑动操作。我想添加一个删除行的操作。
我的测试表视图显示从0到9的数字,数据源是一个简单的整数数组,称为numbers:
class ViewController: UIViewController {
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
}
Run Code Online (Sandbox Code Playgroud)
选择一行时,我将打印以下相关值numbers:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print(numbers[indexPath.row])
tableView.deselectRow(at: indexPath, animated: true)
}
Run Code Online (Sandbox Code Playgroud)
我实现新的委托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])
}
Run Code Online (Sandbox Code Playgroud)
当我在行上滑动时,删除工作正常。但是,这就是我的问题,当我在删除后选择另一行时,关联的IndexPath错误...
例:
我做错了什么?
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)
Run Code Online (Sandbox Code Playgroud)
And always remember that if you change with the model you need to update the view.
| 归档时间: |
|
| 查看次数: |
1532 次 |
| 最近记录: |