如何禁用Copy&在UITextfield中定义UIMenuController的UIMenuItems

时间:2015-01-02 18:58:49

标签: ios objective-c ios8 uimenucontroller uimenuitem

我正在实施自定义UIMenuController并试图找出答案。如何合法禁用UIMenuControllerUITextfield的“复制”和“定义”UIMenuItems? Textfield不可编辑。我尝试使用以下方法禁用“复制”:

-(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];
}

但菜单仍显示“复制”和“定义”UIMenuItems。如何禁用它们,只留下我的物品?

5 个答案:

答案 0 :(得分:7)

最后通过继承UITextView(为它创建自定义类)并添加

来解决它
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{

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

    return NO;
}

我的自定义TextView子类的.m文件内部。

之后"复制"不论是否有[menu update];

,都不会再出现

答案 1 :(得分:4)

在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方法来通知它实现它。

答案 2 :(得分:1)

您可以通过继承UITextField类并重写其canPerformAction::方法来创建类。

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

答案 3 :(得分:1)

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

    override public 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!

答案 4 :(得分:0)

设置菜单项后添加此项

[menu update];

我希望这能解决您的疑问。 :)