oyalhi
oyalhi

Reputation: 3994

shouldShowMenuForRowAt not being called

First time trying to implement a menu. I have a custom UITableViewCell used in UITableView in a UITableViewController. TableView is configured as follows:

fileprivate configureTableView() {
    tableView.register(UINib(nibName: TransactionTableViewCell.nibName, bundle: nil), forCellReuseIdentifier: TransactionTableViewCell.identifier)
    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = TransactionEntryTableViewCell.defaultHeight
}

I create the cell below like so:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    switch indexPath.section {
    case 0:
        guard let cell = tableView.dequeueReusableCell(withIdentifier: TransactionTableViewCell.identifier, for: indexPath) as? TransactionTableViewCell else { DLog("ERROR getting TransactionTableViewCell"); return UITableViewCell() }
        let entry = entries[indexPath.row]
        cell.entry = entry
        return cell

    case 1:
        let cell = tableView.dequeueReusableCell(withIdentifier: "newTransactionCell", for: indexPath)
        cell.textLabel?.text = Strings.AddANewTransaction
        return cell

    default:
        assert(false)
        return UITableViewCell()
    }

Menu related methods are as follows:

override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
    print("shouldShowMenuForRowAt")
    return true
}

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    print("canPerformAction")
    return action == MenuAction.duplicate.selector()
}

override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
    print("action = \(action)")
}

All seems to be working fine; however, the method shouldShowMenuForRowAt is not being called when long pressed on the table.

I have a sample project that works fine. However, this is not working. Any ideas what could be the reason?

Upvotes: 0

Views: 1038

Answers (2)

Marc Etcheverry
Marc Etcheverry

Reputation: 1089

You problem is that you implemented

override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool

Not the actual required method:

override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool

You are welcome, I wasted an hour with this exact same issue!

Upvotes: 1

Max Potapov
Max Potapov

Reputation: 1337

You should override UITableViewDelegate method instead of NSObject:

override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
    return action == MenuAction.duplicate.selector()
}

Upvotes: 1

Related Questions