I'm trying to enable a custom UIMenuController that is activated inside a UITextView. In my viewDidLoad() I have the following code:
override func viewDidLoad() {
super.viewDidLoad()
self.noteTextView.delegate = self
let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(enableCustomMenuControllerAtTap(_:)))
self.noteTextView.addGestureRecognizer(tapGesture)
}
The method that handles the gesture is:
func enableCustomMenuControllerAtTap(_ gesture: UITapGestureRecognizer) {
print("tap")
view.becomeFirstResponder()
let OP1MenuController: UIMenuController
OP1MenuController = UIMenuController.shared
let font = UIMenuItem(title: "Font", action: #selector(pickFont))
let color = UIMenuItem(title: "Color", action: #selector(pickColor))
OP1MenuController.menuItems = [font, color]
let point = gesture.location(in: view)
OP1MenuController.setTargetRect(CGRect(x: point.x, y: point.y, width: 200, height: 200), in: view)
OP1MenuController.arrowDirection = UIMenuControllerArrowDirection.down
OP1MenuController.setMenuVisible(true, animated: true)
}
Next I implemented these methods, as I have seen in many guides:
func pickFont(sender: UIMenuItem) {
}
func pickColor(sender: UIMenuItem) {
}
override var canBecomeFirstResponder: Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if action == Selector(("pickFont")) || action == Selector(("pickColor"))
{
if (noteTextView.selectedRange.length > 0) {
return true
}
}
return false
}
Can someone tell me why is the menu not displaying? Any help would be really appreciated.
Okay, the menu wasn't showing because I was using a different type of selector in the canPerformAction() method. I had to use the #selector(method) type in order to implement and display my custom menu item actions.