Question

I understand that you use (BOOL)control:(NSControl *)control textView:(NSTextView *)inputfield doCommandBySelector:(SEL)commandSelector to detect the key for NSTextView and NSTextField that the user has pressed like the following.

- (BOOL)control:(NSControl *)control textView:(NSTextView *)inputfield doCommandBySelector:(SEL)commandSelector 
    {
    if(commandSelector == @selector(insertNewline:) )
        {
            //... a key is down
            return YES;    // We handled this command; don't pass it on
         } 
         else 
         {
            return NO;
         }
    }

My question is how you tell under which text field a key is down when you have multiple such controls. I've set a tag like the following to see if a key is down for a particular text field, but it doesn't work.

- (BOOL)control:(NSControl *)control textView:(NSTextView *)inputfield doCommandBySelector:(SEL)commandSelector 
 {
      if ([inputfield tag] == 100) 
      {
         if(commandSelector == @selector(insertNewline:) )
         {
               //... a key is down
               return YES;    // We handled this command; don't pass it on
         } 
         else 
         {
               return NO;
         }
     }

     else 
     {
        return NO;
     }
 }

Thank you for your advice.

Was it helpful?

Solution

Did you wonder, why it is typed as a text view even you have a text field?

The reason for your problem is that editing is not done by the control itself, but the field editor (usually a single instance per window). You ask that field editor for its tag and will probably get the result -1. (Which means something like no tag.)

The "real" text field is the delegate of the field editor. To get it, you have to ask the parameter for its delegate. Next, you should not use a tag but set outlets to the text fields and compare the pointers. (It is a little bit tricky because of the typing.)

- (BOOL)control:(NSControl *)control textView:(NSTextView *)inputfield doCommandBySelector:(SEL)commandSelector
{
    id realControl = inputfield.delegate;
    if (realControl == self.field1)
    {
        NSLog(@"I'm 1");
        return YES;    // We handled this command; don't pass it on
    }
    else if (realControl == self.field2)
    {
        NSLog(@"I'm 2");
        return YES;    // We handled this command; don't pass it on
    }

    else
    {
        return NO;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top