UITableView Swipe Action — 客製化滑動按鈕動作

Anny
Oct 19, 2020

--

今天來聊聊 UITableView Swipe Action 滑動按鈕動作吧~~~

向左向右滑動,會出現功能按鈕,還要執行動作~~~

如下圖顯示

原本的版本為

在 iOS 11,更新了!!!

使用 UIContextualAction

tableView(_:trailingSwipeActionsConfigurationForRowAt) 以及tableView(_:leadingSwipeActionsConfigurationForRowAt)

就可以實現 TableView 左滑和右滑 顯示多個可點選執行的 button。

今天更新版本與舊的版本皆會做介紹~~~

如果只是要普通刪除按鈕用法

使用commit editingStyle 即可

客製化向左滑按鈕

想要顯示其他文字的按鈕

使用以下function

使用 UIContextualAction 來製作按鈕

客製化向右滑按鈕

其他注意事項~~~

  1. 記得要呼叫 UIContextualAction 最後一個Bool 回傳值,不然點選 button 後cell 不會回到正常顯示的狀態。
  2. Button 可以更改背景顏色與增加圖片。
  3. 若要防止 cell 滑到底之後,不小心觸發第一個按鈕,可以將 performsFirstActionWithFullSwipe 設為 false。
let prevention = UISwipeActionsConfiguration(actions: [doneAction, undoneAction])prevention.performsFirstActionWithFullSwipe = falsereturn prevention

舊版 editActionsForRowAt 與 UITableViewRowAction

最後介紹一下舊版本,目前是只能左滑。

使用以下function

使用 UITableViewRowAction 來製作按鈕

override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {    let doneAction = UITableViewRowAction(style: .normal, title: "完成了") { (UITableViewRowAction, IndexPathindex:IndexPath) in
self
.label.text = self.todo[indexPath.row] + " 完成了"
}
let undoneAction = UITableViewRowAction(style: .destructive, title: "未完成") { (UITableViewRowAction, IndexPathindex:IndexPath) in
self
.label.text = self.todo[indexPath.row] + " 未完成"
}
return [doneAction, undoneAction]}

完整程式碼

--

--

Anny
Anny

Written by Anny

If You Think You Can, You Can!

No responses yet