Day 19 UItableView的练习 (3/3)

接下来我们可以对我们每笔资料向左滑动後,让他可以被删除

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        list.remove(at: indexPath.row)
        tableview.deleteRows(at: [indexPath], with: .automatic)
    }
    func tableView(_ tableView: UITableView, titleForDeleteConfirmationButtonForRowAt indexPath: IndexPath) -> String? {
        "Deleted"
    }

上面的方法只能让我们左滑删除,假设我们要做更多事呢?

那我们要用到"trailingSwipeActionsConfigurationForRowAt"这个function来帮我们实现,透过这个方法我们可以自订左滑要干嘛

 func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        
        let isfavorite = UIContextualAction(style: .normal, title: "isfavorite") { (action,view,completionHandler) in
            completionHandler(true)

        }
        isfavorite.backgroundColor = .systemBlue
        let del = UIContextualAction(style: .destructive, title: "delete"){
            (action, view, completionHander) in
            self.list.remove(at: indexPath.row)
            self.tableview.deleteRows(at: [indexPath], with: .automatic)
            //你要做的事情
            completionHander(true)
        }
        let config = UISwipeActionsConfiguration(actions: [isfavorite,del])
        config.performsFirstActionWithFullSwipe = false
        return config
    }

为了怕滑到底之後误触按钮,我们可以performsFirstActionWithFullSwip,设定成false

左边的详细资讯可以到Main.storyboard里的cell,右边菜单的"Accessory"更改

再来我们可以学习如何更改储存格的顺序,首先我们要让tableview进入编辑模式,到viewDidLoad新增

tableview.isEditing = true

之後新增这段程序码,让他的储存格可以被移动

 func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
        return true
    }

但是如果要让他从原本的位置移到新的位置,还需要透过底下程序码来实现:

  func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
        let itemToMove = list[sourceIndexPath.row]
        list.remove(at: sourceIndexPath.row)
        list.insert(itemToMove, at: destinationIndexPath.row)
    }

完成後如下:


<<:  Day16 NiFi - 与 MongoDB 对接设定

>>:  Day16 iPhone捷径-媒体Part6

[Day-1] R语言 - 分群纲要(clustering in r)

您的订阅是我制作影片的动力 订阅点这里~ 若内容有误,还请留言指正,谢谢您的指教 ...

Day28 实作信件发送功能(1)

昨天有跟大家卖过关子说之後可能会为各位示范如何发送信件,大家应该都还蛮期待的吧!(应该有吧... 那...

【课程推荐】2021/3/6~3/7 Angular前端开发框架实战

课程目标 ‧ 了解Angular前端开发框架与其优势 ‧ 学会有效率的利用Angular开发前端网页...

恳求解答

恳求解答 Microsoft 的 Configuration Manager 与Windows Se...

Day 0xE - 建立订单纪录到资料库

0x1 前言 目前还没有画面可以看或操作,所以单就资料流的部分先写进资料库, 而建立订单目前也是先塞...