Reputation: 69
I'm trying to add a custom action to UIMenuController
for use of on a UITableViewCell
and it doesn't appear when the menu is shown.
Edit: Revised code.
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
override func viewDidLoad() {
...
UIMenuController.shared.menuItems = [UIMenuItem(title: "Test", action: #selector(test))]
UIMenuController.shared.update()
}
// Table view setup
// ...
func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return action == #selector(copy(_:)) || action == #selector(test)
}
func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(test)
}
@objc func test() {
print("Hello, world!")
}
}
Upvotes: 0
Views: 251
Reputation: 780
test
function needs to be in the UITableViewCell
subclass.canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool
in that UITableViewCell
subclass and return return action == #selector(test)
UIMenuController.shared.menuItems = [UIMenuItem(title: "Test", action: #selector(test))]
change #selector(test)
to #selector(YourCellSubclass.test)
.|| action == #selector(test)
to || action == #selector(YourCellSubclass.test)
EDIT: Adding working example.
ViewController:
class ViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
UIMenuController.shared.menuItems = [UIMenuItem(title: "Test", action: #selector(MyCell.test))]
UIMenuController.shared.update()
tableView.register(MyCell.self, forCellReuseIdentifier: "my")
// Do any additional setup after loading the view, typically from a nib.
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "my", for: indexPath) as! MyCell
cell.textLabel?.text = "\(indexPath.row)"
return cell
}
override func tableView(_ tableView: UITableView, shouldShowMenuForRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, canPerformAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) -> Bool {
return action == #selector(MyCell.test)
}
override func tableView(_ tableView: UITableView, performAction action: Selector, forRowAt indexPath: IndexPath, withSender sender: Any?) {
// needs to be here
}
}
Cell:
class MyCell: UITableViewCell {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(test)
}
@objc func test() {
print("works")
}
}
Upvotes: 1