如何在 UITextfield 中禁用复制和定义 UIMenuController 的 UIMenuItems

How to disable Copy & Define UIMenuItems of UIMenuController in UITextfield

我正在实施自定义 UIMenuController 并试图找出答案。我如何合法禁用 UITextfieldUIMenuController 的 "Copy" 和 "Define" UIMenuItems?文本字段不可编辑。我试图禁用 "Copy" 使用:

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender 
{
   if (action == @selector(copy:))
    {
        return NO;
    }

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


- (IBAction)tapTextViewGesture:(id)sender {

  UIMenuItem *myItem1 = [[UIMenuItem alloc] initWithTitle:@"myItem1" action:@selector(myItem1Pressed:)];
  UIMenuItem *myItem2 = [[UIMenuItem alloc] initWithTitle:@"myItem2" action:@selector(myItem2Pressed:)];
  UIMenuItem *myItem3 = [[UIMenuItem alloc] initWithTitle:@"myItem3" action:@selector(myItem3Pressed:)];

    // Access the application's shared menu
    UIMenuController *menu = [UIMenuController sharedMenuController];

    [menu setMenuItems:[NSArray arrayWithObjects:myItem1,myItem2,myItem3, nil]];

    CGRect menuRect = CGRectMake(20, 50, 200, 0);


    // Show the menu from the cursor's position
    [menu setTargetRect:menuRect inView:self.view];


    [menu setMenuVisible:YES animated:YES];
}

但菜单仍然显示 "Copy" 和 "Define" UIMenuItems。我怎样才能禁用它们,只留下我的物品?

最终通过 subclassing UITextView 解决了它(为其创建了自定义 class)并添加了

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

    if (action == @selector(copy:))
    {
        return NO;
    }

    return NO;
}

在我的自定义 TextView 子 class.

.m 文件中

之后 "Copy" 不再出现,有或没有 [menu update];

您可以通过 subclassing UITextField class 并覆盖其 canPerformAction:: 方法来创建 class 来实现。

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    // Returning 'NO' here disables all actions on textfield
    return NO;
}

在viewController.m中实现这个实例方法:

**- (BOOL)canPerformAction:(SEL)action withSender:(id)sender {
    if ([_targetTextField isFirstResponder]) {
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [[UIMenuController sharedMenuController] setMenuVisible:NO animated:NO];
        }];
    }
    return [super canPerformAction:action withSender:sender];
}**

此方法检查目标文本字段是否是第一响应者。如果是,NSOperationQueue 为 sharedMenuController 操作创建一个单独的线程,将其可见性和动画设置为 no,使其无法进行复制、粘贴等操作。 return语句调用UIResponder的canPerformAction方法通知其实现

Swift 4.2. && Xcode 10 对我有用:

public extension UITextView {
    override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        // Requested action to prevent:
        guard action != #selector(copy(_:)) else { return false }      // disabling copy

        // Further actions to prevent:
        // guard action != #selector(cut(_:)) else { return false }    // disabling cut
        // guard action.description != "_share:" else { return false } // disabling share
        return super.canPerformAction(action, withSender: sender)
    }
}

为了完成这项工作,您必须创建 UITextField/UITextView 的子类,并确保在 super.canPerformAction(_:withSender:)!

上调用 super