0

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.

El Tomato
  • 6,479
  • 6
  • 46
  • 75

1 Answers1

0

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;
    }
}
Amin Negm-Awad
  • 16,582
  • 3
  • 35
  • 50
  • Hmm... I don't know how you figure that out. That works. Yes, what you are saying does make sense. But I don't think I could have figure that out by myself. Objective-C is complicated. Anyway, thanks a lot. – El Tomato Jun 11 '13 at 12:49
  • This system has its tradition in the early beginnings of NextStep. At that time optimization was important to a framework for GUI. It's the same with cells on Mac OS. https://www.youtube.com/watch?v=j02b8Fuz73A – Amin Negm-Awad Jun 11 '13 at 15:17