Ekra
Ekra

Reputation: 3301

UITableVIew swipe trailingSwipeActionsConfigurationForRowAt not working

New iOS 11 UITableView Swipe action not getting called. The delegate and datasource are working fine for the table.

I am not able to swipe and see the menu items.

Below is my code for the same.

func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let contextItem = UIContextualAction(style: .normal, title: "Leading & .normal") { (contextualAction, view, boolValue) in
        print("Leading Action style .normal")
    }
    let swipeActions = UISwipeActionsConfiguration(actions: [contextItem])

    return swipeActions
}

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let contextItem = UIContextualAction(style: .destructive, title: "Trailing & .destructive") { (contextualAction, view, boolValue) in
        print("Trailing Action style .destructive")
    }
    let swipeActions = UISwipeActionsConfiguration(actions: [contextItem])

    return swipeActions
}

I tried to call below and its working fine.

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {

    }
}

Any hint in right direction is highly appreciated.

Upvotes: 4

Views: 5687

Answers (3)

ysnzlcn
ysnzlcn

Reputation: 618

For those who uses UITableViewDiffableDataSource you need to subclass it and override its canEditRowAt method.

public override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    true
}

Upvotes: 2

DeeNove750
DeeNove750

Reputation: 63

Code looks good, but you are missing probably missing the following the "UITableViewDelegate" in the Class declaration and also the "TableView.delegate = self" in the viewdidload() section. So it should look like:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

   override func viewDidLoad() {
      super.viewDidLoad()
      tableView.dataSource = self
      tableView.delegate = self
   }

}

Upvotes: 1

Au Ris
Au Ris

Reputation: 4659

You need to pass true to UIContextualAction in the closure boolValue(true). Otherwise the handler won't allow the action.

func tableView(_ tableView: UITableView, leadingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let contextItem = UIContextualAction(style: .normal, title: "Leading & .normal") { (contextualAction, view, boolValue) in
        boolValue(true) // pass true if you want the handler to allow the action
        print("Leading Action style .normal")
    }
    let swipeActions = UISwipeActionsConfiguration(actions: [contextItem])

    return swipeActions
}

Upvotes: 4

Related Questions