swiftuitableviewtableview

How to get the index of the array from a TableViewCell when executing a contextmenue action


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UIContextMenuInteractionDelegate {

    @IBOutlet weak var plannerTableView: UITableView!

    ...  
  

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myPreparedTasks.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let task = self.myPreparedTasks[indexPath.row]
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "taskCell", for: indexPath) as! TaskTableViewCell
        cell.taskId?.text = task.id

        let interaction = UIContextMenuInteraction(delegate: self)
        cell.addInteraction(interaction)

        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50
    }



    func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
        return UIContextMenuConfiguration(identifier: nil, previewProvider: nil, actionProvider: { suggestedActions in
            return self.makeContextMenu()
        })
    }
    
    func makeContextMenu() -> UIMenu {
        let add = UIAction(title: "Neuer Task", image: UIImage(systemName: "plus.square")) { action in
            // Show the Task ID
        }

        return UIMenu(title: "Task", children: [add])
    }

}

iOS 13, Swift 5

Hi. This is the first time I implement a context menue in a TableViewCell. I do the stuff above. And it looks great. But I can not get the ID of the myPreparedTasks array from the tableview content. How can I get this id? Please give me an answer for this construct. I see many other constructs in the net but I don't understand it yet.

Many thanks Jens


Solution

  • For a context menu in a table view you have to implement the delegate method

    optional func tableView(_ tableView: UITableView, 
                  contextMenuConfigurationForRowAt indexPath: IndexPath, 
                  point: CGPoint) -> UIContextMenuConfiguration?
    

    rather than adding an UIContextMenuInteraction to each cell.