Programmatically call textFieldShouldReturn

亡梦爱人 提交于 2019-12-13 00:47:59

问题


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".


回答1:


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];
    }
}



回答2:


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.



来源:https://stackoverflow.com/questions/11932166/programmatically-call-textfieldshouldreturn

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!