SwiftUI - Custom Swipe Actions In List

后端 未结 3 730
一整个雨季
一整个雨季 2020-12-03 05:29

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         


        
3条回答
  •  时光说笑
    2020-12-03 05:46

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

提交回复
热议问题