【问题标题】:How to get the index of the array from a TableViewCell when executing a contextmenue action执行上下文菜单操作时如何从 TableView 单元中获取数组的索引
【发布时间】:2020-09-25 13:01:31
【问题描述】:
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、斯威夫特 5

嗨。这是我第一次在 TableViewCell 中实现上下文菜单。我做上面的事情。 它看起来很棒。但我无法从 tableview 内容中获取 myPreparedTasks 数组的 ID。 我怎样才能得到这个ID?请给我这个构造的答案。我在网上看到了许多其他的构造,但我还不明白。

非常感谢 延斯

【问题讨论】:

    标签: swift uitableview tableview


    【解决方案1】:

    对于表格视图中的上下文菜单,您必须实现委托方法

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

    而不是为每个单元格添加UIContextMenuInteraction

    【讨论】:

      猜你喜欢
      • 2020-02-12
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多