[英]Programmatically call textFieldShouldReturn
當前項目在cocos2d v2下運行。
我有一個簡單的UITextField添加到CCLayer。
每當用戶觸摸textField時,就會出現一個鍵盤。
然后當用戶觸摸“返回”按鈕時,鍵盤消失並清除輸入。
我試圖做的是當用戶觸摸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在textfield為“resignFirstResponder”時輸入此textFieldShouldReturn。
來自Apple文檔 :
textFieldShouldReturn:詢問委托文本字段是否應該按下返回按鈕。
因此只有在用戶點擊返回按鈕時才會調用它。
我寧願創建一個計算和輸入清除的方法,並在您希望它被調用時調用該方法。 例:
- (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];
}
}
正如@matsr建議的那樣,您應該考慮重新組織程序邏輯。 對於UITextField上的resignFirstResponder
來說,調用textFieldShouldReturn:(UITextField *)textField
是沒有意義的,因為通常會從該方法中調用resignFirstResponder。 此外,您不應嘗試以編程方式調用textFieldShouldReturn
。
相反,我建議將你的計算代碼移動到你的控制器中的一個新方法中,然后在textFieldShouldReturn
和你在UITextField上調用resignFirstResponder
的觸摸時調用resignFirstResponder
。
這也有助於實現事件處理代碼與計算/邏輯代碼的分離。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.