others-how to add context menu with custom actions to tableview controller?
1. Purpose
In this post, I would demo how to add context menu with custom actions to tableview controller.
2. Environment
- Mac OS 10.15
- Swift 5
- Xcode 12
3. The solution
Here is the code:
override func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
if let item = messages[indexPath.row] as? Message {
return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { suggestedActions in
// Create an action for sharing
let star = UIAction(title: "star", image: UIImage(systemName: "star")) { action in
print("Staring \(item)")
self.performStar(msg: item)
}
return UIMenu(title: "", children: [star])
}
}
return nil
}
The key point is as follows:
// Create an action for sharing
let star = UIAction(title: "star", image: UIImage(systemName: "star")) { action in
print("Staring \(item)")
self.performStar(msg: item)
}
return UIMenu(title: "", children: [star])
Now it works!
4. Summary
In this post, I demonstrated how to add context menu with custom actions to tableview controller.