我正在尝试向UIMenuController
添加自定义操作,以在UITableViewCell
上使用,并且在显示菜单时不会显示。
编辑:修改后的代码。
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!")
}
}
答案 0 :(得分:1)
test
函数必须位于UITableViewCell
子类中。canPerformAction(action: Selector, withSender sender: AnyObject?) -> Bool
子类中实现UITableViewCell
并返回return action == #selector(test)
UIMenuController.shared.menuItems = [UIMenuItem(title: "Test", action: #selector(test))]
中,将#selector(test)
更改为#selector(YourCellSubclass.test)
。|| action == #selector(test)
更改为|| action == #selector(YourCellSubclass.test)
编辑: 添加工作示例。
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
}
}
单元格:
class MyCell: UITableViewCell {
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
return action == #selector(test)
}
@objc func test() {
print("works")
}
}