2010-05-04 131 views
1

驗證UITextField中的用戶輸入並顯示錯誤的最佳做法是什麼?我嘗試在textFieldShouldReturntextFieldShouldEndEditing內執行檢查,並在userever輸入無效內容時彈出錯誤框。驗證UITextField輸入並顯示錯誤

但是,在測試期間,從textFieldShouldEndEditing彈出多次調用。我的簡單測試是在TextFieldA中輸入無效文本並直接導航到TextFieldB。我觀察到3個錯誤彈出窗口,所有產生的textFieldShouldReturn

+0

是您的UITextField委託多個領域的代表,或只是一個? – Ricky 2011-03-24 06:11:53

回答

0

這可能是通過展示警報,編輯欄失去焦點,並由此發出另一個textFieldShouldReturn或textFieldShouldEndEditing。

嘗試推遲警報,通過將代碼,以顯示警報到一個單獨的方法,和從textFieldShouldEndEditing調用該方法使用[自performSelector:@selector(yourAlertMethod)withObject:無afterDelay:0]

其實,我發現前段時間我有類似的問題。訣竅是確保文本字段在顯示警報的持續時間內不再有焦點。

這裏是我的解決方案:

// declare this in your interface as part of your ivars: 
UITextField *currTextField; 

// here comes the code to check for bad input and show an alert: 

#pragma mark - 
#pragma mark UITextFieldDelegate 

- (BOOL)textFieldShouldReturn:(UITextField *)textField 
{ 
    if ([self acceptsEntry:textField.text]) { // this checks if the text is valid 
     // We're done here 
     return YES; 
    } else { 
     // Setting the delegate to nil will prevent the textField to listen for Return key events. 
     textField.delegate = nil; 

     // Removing the observer will prevent the user from typing into the textfield using an external keyboard 
     [textField resignFirstResponder]; 

     currTextField = textField; 

     UIAlertView *av = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"invalidEntry", @"") 
                message:NSLocalizedString(@"invalidEntryMessage", @"") 
                delegate:self 
              cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil]; 
     [av show]; 
     [av release]; 
    } 
    return NO; 
} 

#pragma mark - 
#pragma mark UIAlertViewDelegate 

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex 
{ 
    // gets called when the user dismisses the alert view 
    currTextField.text = @""; // erase bad entry 
    currTextField.delegate = self; // We want to listen for return events again 
    [currTextField becomeFirstResponder]; 
    currTextField = nil; 
}