user3069232 user3069232 - 10 days ago 6
iOS Question

Disabling some of UITextView actions on editable text

iOS 10. Swift 3

I put this into my class with the UITextView. Seemed to be the best answer for removing some of the functionality in a popup menu. Initially had a issue with it crashing and I accepted and voted the answer as correct... but on further testing..

I sadly find it infact does nothing, absolutely nothing!! beyond compiling seemly catching the menu options and than doing them anyway, even if I trying to ignore them.

It seems it used to work in objective C as far as I can tell in other SO posts, but not in Swift? Has anybody managed to get a working version in Swift that looks like this perhaps, with some subtle code change I am missing here.

override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
if (action == #selector(cut)) {
return false
}
return super.canPerformAction(action, withSender: sender)
}

Answer

You need to reorganize your implementation a bit. It should be:

override public func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
    if (action == #selector(delete)) {
        return false
    } else {
        return super.canPerformAction(action, withSender: sender)
    }
}

As you had it, you were ignoring the result of super.canPerformAction and always returning true. That's bad because your class doesn't respond to every single selector.