0

I subclass a NSTextField and in subclass use an event method (keyUp),i want to call a method in main view (view that i put NSTextFiled on it) when user push Enter key.i use below code but don't how to call specific method in main view

- (void)keyUp:(NSEvent *)theEvent
{
    NSString *theArrow = [theEvent charactersIgnoringModifiers];
    unichar keyChar = 0;
    keyChar = [theArrow characterAtIndex:0];
    if ( keyChar == NSEnterCharacter )
    {
        //call method that exist in main view   
    }   
}

3 Answers3

1

This should do it...

SEL sel = @selector(textFieldDidPressEnter:);

if (self.delegate && [self.delegate respondsToSelector:sel]) {
    [self.delegate performSelector:sel withObject:self];
}

Then make sure the class you want to have this message is set as the delegate. The more complete answer is to also declare textFieldDidPressEnter: as part of the delegate protocol. Here's a good resource on how to do that.

Community
  • 1
  • 1
danh
  • 62,181
  • 10
  • 95
  • 136
  • can you explain where should i enter this code ?and how to set class as delegate? –  Apr 28 '12 at 19:44
  • sure. right where you have the comment // call method that exist in main view. Wherever the main view sets up the textField, you can say textField.delegate = self; The "self" needs to be declared as conforming to , and it needs to implement the method name I made up: textFieldDidPressEnter. You can change that name as you wish. – danh Apr 28 '12 at 19:47
0

1.in main view set : textField.delegate=self;

2.add <NSTextFieldDelegate> to mainview.h and subclass.h

3.use this code Instead of comment

if ( self.delegate && [self.delegate respondsToSelector:@selector(textFieldDidPressEnter:)] ) 
            [self.delegate performSelector:@selector(textFieldDidPressEnter:) withObject:self];

4.implement this method in mainview.m

-(void)textFieldDidPressEnter:(NSTextField *)txt
{

}
SajjadZare
  • 2,487
  • 4
  • 38
  • 68
0
if ( [self.delegate respondsToSelector:@selector(textFieldDidPressEnter:)] ) 
    [(id)self.delegate textFieldDidPressEnter:self];

no need to use performSelector:

user102008
  • 30,736
  • 10
  • 83
  • 104