热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

UITableView-破坏性的UIContextualAction不会重新加载数据

如何解决《UITableView-破坏性的UIContextualAction不会重新加载数据》经验,为你挑选了1个好方法。

我正在尝试使用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.


推荐阅读
author-avatar
羽星快乐_914_137
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有