How can I use custom Swipe Actions in SwiftUI?
I tried to use the UIKit Framework to get these working in SwiftUI. But that doesn\'t work for me.
imp
Based on Michał Ziobro answer using Introspect to simplify table view delegate setup.
Note that this will override the table view delegate.
struct ListSwipeActions: ViewModifier {
@ObservedObject var coordinator = Coordinator()
func body(content: Content) -> some View {
return content
.introspectTableView { tableView in
tableView.delegate = self.coordinator
}
}
class Coordinator: NSObject, ObservableObject, UITableViewDelegate {
func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
return .delete
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let archiveAction = UIContextualAction(style: .normal, title: "Title") { action, view, completionHandler in
// update data source
completionHandler(true)
}
archiveAction.image = UIImage(systemName: "archivebox")!
archiveAction.backgroundColor = .systemYellow
let configuration = UISwipeActionsConfiguration(actions: [archiveAction])
return configuration
}
}
}
extension List {
func swipeActions() -> some View {
return self.modifier(ListSwipeActions())
}
}