2011-04-20 70 views
0

我正在嘗試創建一個問卷,其中用戶應對1-7中的語句進行評分。文本驗證 - 用戶只能選擇一個數字一次

用戶通過填入UITextFields的值爲1-7之間的值對語句進行評級。

我已經做到這樣,用戶只能寫入1-7之間的值,並且他們只能爲每個文本字段寫入一個字符。

我現在想要做的是防止用戶多次使用該值。

這是我到目前爲止的代碼。

#define CHARACTERS   @"1234567" 

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
// These are the characters that are ~not~ acceptable 
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet]; 

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; 

if (([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] >1) | ([newString length] > 1)) 
return NO; 
else 
return YES; 
} 
+0

你的意思是,如果用戶通過輸入文本「1」來評價,那麼另一個文本框不應該包含「1」,對嗎? – dks1725 2011-04-20 13:02:06

+0

是的,你是對的。 – Makkafella 2011-04-20 13:04:45

+0

@ dks1725 [tf1.text isEqualToString:string]解決了它! (tf1是其中一個textfield的出口) – Makkafella 2011-04-20 14:44:03

回答

-1

在創建UITextField時,將keyboardType設置爲UIKeyboardTypeNumberPad。

-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 

{ 
    if([[textField text]length]==1) 
    //perform condition 

    else 
    //perform condition 
} 

這可能幫助

+1

這並不能解決唯一性問題。這強制執行長度1,他已經執行。 – Rayfleck 2011-04-20 13:17:42

0


你可以做一兩件事給標籤的所有文本框,並檢查你當前的文本框輸入的字符串是否相同,所有其他文本框的文本,然後返回NO。

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
// These are the characters that are ~not~ acceptable 
NSCharacterSet *unacceptedInput = [[NSCharacterSet characterSetWithCharactersInString:CHARACTERS] invertedSet]; 

NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; 

if (([[string componentsSeparatedByCharactersInSet:unacceptedInput] count] >1) | ([newString length] > 1)) 
    return NO; 
else 
    //Call function to check if string is same as other textfield.text then return NO else YES 
} 

其他
另一種選擇是,當你進入你可能需要1串並保存的TextField.text在串並更新所有的時間和它檢查您輸入的字符串是否是在該字符串的子字符串。 祝你好運

1

我會用字典。每當在文本字段中選擇一個數字時,檢查字典是否具有該值。如果它沒有值,則輸入的值是正確的。現在將條目添加到字典中,然後讓用戶進入下一個文本字段。如果您對所有文本字段重複此過程,您將很容易解決此問題。

相關問題