如何禁用粘贴到NSSecureTextField的密码

时间:2013-09-23 11:58:59

标签: objective-c macos cocoa paste nstextfield

我已经做了很长时间了,尝试了两种方法。但是,都没有成功。

  1. 继承NSSecureTextField并覆盖-(BOOL)becomeFirstResponder-(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];
    }
    

1 个答案:

答案 0 :(得分:0)

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

1)在屏幕截图中附上mainmenu.xib中设置menuitem粘贴的标签值,然后阻止以下方法: -

enter image description here

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