0

我已经研究了很长时间,并尝试了以下两种方法。但是,都没有成功。

  1. 子类化NSSecureTextField和覆盖-(BOOL)becomeFirstResponderand -(void)textDidEndEditing:.

    -(BOOL) becomeFirstResponder
    {
        NSMenu *mainMenu = [[NSApplication sharedApplication]mainMenu];
        NSMenu *appMenu = [[mainMenu itemAtIndex:2]submenu];
        NSLog(@"%@", [appMenu title]);
        for (NSMenuItem *item in [appMenu itemArray]) {
            if ([[item title] isEqual: @"Paste"])
            {
                NSLog(@"%@", [item title]);
                [item setEnabled:NO];             
            }
        }
        return [super becomeFirstResponder];
    }
    
    - (void)textDidEndEditing:(NSNotification *)notification
    {
        NSMenu *mainMenu = [[NSApplication sharedApplication]mainMenu];
        NSMenu *appMenu = [[mainMenu itemAtIndex:2]submenu];
        NSLog(@"%@", [appMenu title]);
        for (NSMenuItem *item in [appMenu itemArray]) {
            if ([[item title] isEqual: @"Paste"])
            {
                NSLog(@"%@", [item title]);
                [item setEnabled:YES];             
            }
        }
    }
    
  2. 将协议添加NSUserInterfaceValidation到的子类NSSecureTextField(也许它不是实现此协议的正确目标,因为永远不会触发此函数中的断点)。

    - (BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)anItem
    {
      SEL theAction = [anItem action];
      if (theAction == @selector(paste:)) {
      return NO;
      }
      return [super validateUserInterfaceItem:anItem];
    }
    
4

1 回答 1

0

在您的文本字段委托方法中,检查菜单项粘贴标记值是否应该匹配,然后不允许将字符粘贴到下面的特定 NSSecureTextField 中:-

1)在mainmenu.xib中设置menuitem paste的标签值,如截图所示,然后执行以下方法:-

在此处输入图像描述

-(void)controlTextDidChange:(NSNotification *)obj
{
    NSMenu *mainMenu = [[NSApplication sharedApplication]mainMenu];
    NSMenu *appMenu = [[mainMenu itemAtIndex:2]submenu];
    BOOL isAllowPaste=YES;
    NSLog(@"%@", [appMenu title]);
    for (NSMenuItem *item in [appMenu itemArray]) {
        if ([item tag] ==1)
        {
            NSLog(@"%@", [item title]);
            isAllowPaste=NO;
        }

    }
    if (isAllowPaste==NO && [obj object]==secureTextField)
    {
            NSLog(@"Cannot paste");
           isAllowPaste=YES;
    }
    }
于 2013-09-25T07:28:40.557 回答