以编程方式调用textFieldShouldReturn

当前项目在cocos2d v2下运行。

我有一个简单的UITextField添加到CCLayer。

每当用户触摸textField时,都会出现一个键盘。

然后当用户触摸“返回”button时,键盘消失并清除input。

我试图做的是当用户触摸UITextField之外的任何地方时做同样的事情。

我find了一个方法,它的工作原理:

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

但是,此方法不会调用该函数:

 - (BOOL)textFieldShouldReturn:(UITextField *)textField 

我用这个函数做一些计算并清除input。 因此,当文本字段为“resignFirstResponder”时,我希望ccTouchesBegininput此文本FieldShouldReturn。

从苹果文档 :

textFieldShouldReturn:询问委托人文本字段是否应该按下返回button。

所以只有当用户点击返回button时才被调用。

我宁愿创build一个计算和input清除的方法,并调用该方法,只要你想要它被调用。 例:

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

正如@matsrbuild议的,你应该考虑重新组织你的程序逻辑。 对于UITextField上的resignFirstResponder调用textFieldShouldReturn:(UITextField *)textField没有任何意义,因为在该方法中通常会调用resignFirstResponder。 另外,您不应该尝试以编程方式调用textFieldShouldReturn

相反,我build议移动你的计算代码到你的控制器/任何新的方法,并调用textFieldShouldReturn和当你处理触摸你在UITextField调用resignFirstResponder

这也有助于实现事件处理代码与计算/逻辑代码的解耦。