2

我正在实施自定义UIMenuController并试图弄清楚。如何合法禁用 in 的“复制”和“定义” UIMenuControllerUIMenuItems UITextfield?文本字段不可编辑。我尝试使用以下方法禁用“复制”:

-(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。如何禁用它们,只留下我的物品?

4

4 回答 4

7

最后通过子类化解决它UITextView(为其创建自定义类)并添加

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

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

    return NO;
}

在我的自定义 TextView 子类的 .m 文件中。

之后“复制”不再出现,有或没有[menu update];

于 2015-01-06T21:02:58.020 回答
5

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

于 2017-03-09T13:10:26.170 回答
2

斯威夫特 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 on super.canPerformAction(_:withSender:)

于 2018-11-01T15:03:56.517 回答
1

您可以通过子UITextField类化类并覆盖其canPerformAction::方法来创建一个类。

-(BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    // Returning 'NO' here disables all actions on textfield
    return NO;
}
于 2015-09-16T14:49:18.033 回答