ios - 以编程方式调用 textFieldShouldReturn

标签 ios cocos2d-iphone uitextfield

当前项目运行在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/

相关文章:

ios - reachabilityWithAddress 在 Objective C 编程中不起作用

objective-c - 我应该释放一个被移除的 child 吗?

ios - 如何在 React Native 中实现单选按钮

IOS,是否有 facebook 和 twitter 委托(delegate) "didShare"?

iphone - Cocos2d、iOS 6.1、GameCenter 显示排行榜时崩溃

iphone - 在Cocos2d中,通过多层按钮,如何控制对用户触摸使用react的按钮?

iphone - -(void)textFieldDidBeginEditing :(UITextField *)sender. 。当我选择文本字段时不会调用此函数?

iphone - 在 becomeFirstResponder 或 resignFirstResponder 的情况下将对象保持在键盘顶部?

html - Angular 4 使用箭头键从文本字段滚动到 <li>

ios - 获取自定义键盘的高度(iOS 8)