-->

How to remove Copy,Select All,Define menuItem from

2020-07-22 17:49发布

问题:

As my this question Display i want to display pop up when user select the text. and in that pop up detail about that word will be displayed.

But i didn't get any satisfactory answer so i have change my logic.

Now i want to display one item like Pop-Up in my UIMenuController and when user click that option than pop-up will displayed.

I have achieved this using this code,

UIMenuItem *menuItem = [[UIMenuItem alloc] initWithTitle:@"Pop-Up" action:@selector(displayPopUp:)];
    [[UIMenuController sharedMenuController] setMenuItems:[NSArray arrayWithObject:menuItem]];

So my option is displaying and when i click that option than pop-up displays.But some other option is also display which i don't wanna, like this

I have googled it and get this code

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender

{    
[UIMenuController sharedMenuController].menuVisible = NO; //do not display the menu
if (action == @selector(copy:))
{

    return NO;  

}

else  if (action == @selector(selectAll:))
{
    return NO; 

}

[self resignFirstResponder];                      //do not allow the user to selected anything
return NO;

return [super canPerformAction:action withSender:sender];
}

But it didn't remove this extra item in UIMenuController.

回答1:

The canPerformAction method is sent to everyone in the Responder chain. So, if the code you mention above is in the ViewController but the UITextView is the first Responder, it will not work. I found that the easiest thing to do was subclass UITextView and put the canPerformAction code in there. I disable all the default menuItems and create a menu of my own.

class rtfView: UITextView {

override func canPerformAction(_ action: Selector, withSender sender: Any!) -> Bool {

    if (action == #selector(textItem(_:))) || (action == #selector(h1Item(_:))) || (action == #selector(h2Item(_:))) || (action == #selector(h3Item(_:))) {
        return true
    } else {
        return false
    }

}

}