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?请给我这个构造的答案。我在网上看到了许多其他结构,但我还不明白。
非常感谢 延斯
对于表视图中的上下文菜单,您必须实现委托方法
optional func tableView(_ tableView: UITableView,
contextMenuConfigurationForRowAt indexPath: IndexPath,
point: CGPoint) -> UIContextMenuConfiguration?
而不是向每个单元格添加
UIContextMenuInteraction
。
如果您打算在表格视图上使用上下文菜单,那么您应该使用 UITableViewDelegate 函数
tableView(_:contextMenuConfigurationForRowAt:点:)
在此函数中,您可以根据需要使用indexPath。