Kalzem
Kalzem

Reputation: 7501

Programmatically call textFieldShouldReturn

The current project runs under cocos2d v2.

I have a simple UITextField added to a CCLayer.

Whenever, the user touch the textField, a keyboard appears.

Then when the user touch the "return" button, the keyboard disappear and clears the input.

What I tried to do is to make the same thing when the user touches anywhere outside the UITextField.

I did find a method and it works :

- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    UITouch* touch = [touches anyObject];
    if(touch.view.tag != kTAGTextField){
        [[[[CCDirector sharedDirector] view] viewWithTag:kTAGTextField] resignFirstResponder];
    }
}

However, this method doesn't call the function :

- (BOOL)textFieldShouldReturn:(UITextField *)textField

I use this function to do some calculation and clear the input. Therefore, I would like ccTouchesBegan to enter this textFieldShouldReturn when the textfield is "resignFirstResponder".

Upvotes: 2

Views: 5116

Answers (2)

matsr
matsr

Reputation: 4267

From the Apple docs:

textFieldShouldReturn: Asks the delegate if the text field should process the pressing of the return button.

So it is only called when the user taps the return button.

I would rather create a method for the calculation and input clearing, and call that method whenever you want it to be called. Example:

- (void)calculateAndClearInput {
    // Do some calculations and clear the input.
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // Call your calculation and clearing method.
    [self calculateAndClearInput];
    return YES;
}

- (void)ccTouchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
    UITouch* touch = [touches anyObject];
    if (touch.view.tag != kTAGTextField) {
        [[[[CCDirector sharedDirector] view] viewWithTag:kTAGTextField] resignFirstResponder];
        // Call it here as well.
        [self calculateAndClearInput];
    }
}

Upvotes: 4

jstr
jstr

Reputation: 1281

As @matsr suggested, you should consider reorganising your program logic. It doesn't make sense for resignFirstResponder on a UITextField to call textFieldShouldReturn:(UITextField *)textField, because often resignFirstResponder is called from within that method. In addition you shouldn't attempt to programmatically call textFieldShouldReturn.

Instead I suggest moving your calculation code into a new method in your controller/whatever and calling that both in textFieldShouldReturn and when you handle the touch where you call resignFirstResponder on the UITextField.

This also helps achieve decoupling of your event handling code from your calculation/logic code.

Upvotes: 1

Related Questions