当前项目运行在cocos2d v2下。
我在 CCLayer 中添加了一个简单的 UITextField。
每当用户触摸文本字段时,就会出现一个键盘。
然后,当用户触摸“返回”按钮时,键盘消失并清除输入。
我试图做的是当用户触摸 UITextField 之外的任何地方时做同样的事情。
我确实找到了一个方法并且它有效:
- (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
我使用这个函数进行一些计算并清除输入。因此,我希望 ccTouchesBegan 在文本字段为“resignFirstResponder”时输入此 textFieldShouldReturn。
最佳答案
来自the Apple docs :
textFieldShouldReturn: Asks the delegate if the text field should process the pressing of the return button.
因此仅当用户点击返回按钮时才会调用它。
我宁愿创建一个用于计算和输入清除的方法,并在需要时调用该方法。示例:
- (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];
}
}
关于ios - 以编程方式调用 textFieldShouldReturn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11932166/