iT邦幫忙

2021 iThome 鐵人賽

DAY 19
0
Mobile Development

IOS菜逼八連續30天挑戰系列 第 19

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

完成後如下:


上一篇
Day 18 UItableView的練習 (2/3)
下一篇
Day 20 捨棄Storyboard並使用XIB來寫app
系列文
IOS菜逼八連續30天挑戰30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言