I am trying to override the default UIMenuController
so that only my custom item "Define..." appears when the user selects text in its text view. I haven't had much luck with the approaches I've found online thus far.
To be more specific, I have subclassed a UIViewController
and used canPerformAction()
to exclude all actions except my define method.
override func becomeFirstResponder() -> Bool {
return true
}
override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
let canPerform: Bool
if action == #selector(defineWord){
canPerform = true
}
else {
canPerform = false
}
print("action = \(action), canPerform = \(canPerform)")
return canPerform
}
In the view controller's viewDidLoad()
, I've included the following:
let shared = UIMenuController.shared
let menuItemDefine = UIMenuItem(title: "Define...", action: #selector(self.defineWord))
shared.menuItems = [menuItemDefine]
Whenever I select text in the view, the console goes through each possible action that might appear in the UIMenuController
and says they can't be performed, with the exception of my custom action:
action = cut:, canPerform = false
action = select:, canPerform = false
(and so on, until...)
action = defineWord, canPerform = true
But the resulting edit menu contains "Copy", "Look Up", "Share", and "Define...". These don't appear in the console, which makes me think that a different approach is called for.
Note that I've also tried subclassing UITextView
and using the above code as appropriate, but the result is the same.
Any ideas where I'm going wrong?