2012-08-13 56 views
1

當前項目在cocos2d v2下運行。以編程方式調用textFieldShouldReturn

我有一個簡單的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 

我用這個功能做了一些計算和清除輸入。因此,當文本字段爲「resignFirstResponder」時,我希望ccTouchesBegan輸入此文本字段應該返回。

+0

BabyAzerty你有沒有找到一種方法如何做到這一點? – Ramis 2016-02-01 14:07:57

回答

3

the Apple docs

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

我有一個問題,只有textFieldShouldReturn:方法沒有被調用。它調用每個其他委託方法,如textFieldDidEndEditing :.你能幫我嗎,http://stackoverflow.com/questions/40474328/textfieldshouldreturn-is-not-called-but-textfielddidendediting-gets-called?noredirect=1#comment68199491_40474328 – 2016-11-08 17:43:53

1

正如@matsr建議的那樣,您應該考慮重新組織您的程序邏輯。對於UITextField上的resignFirstResponder調用textFieldShouldReturn:(UITextField *)textField沒有意義,因爲在該方法中通常會調用resignFirstResponder。此外,您不應嘗試以編程方式致電textFieldShouldReturn

相反,我建議將您的計算代碼移入控制器中的新方法/無論何時調用textFieldShouldReturn以及在UITextField上處理觸摸時調用resignFirstResponder

這也有助於實現事件處理代碼與計算/邏輯代碼的解耦。