Question

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   
    }   
}
Was it helpful?

Solution

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
{

}

OTHER TIPS

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.

if ( [self.delegate respondsToSelector:@selector(textFieldDidPressEnter:)] ) 
    [(id)self.delegate textFieldDidPressEnter:self];

no need to use performSelector:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top