2013-05-10 228 views
-2

我正在創建一個由4個單詞組成的炒文字遊戲,因此有4個文本框。如何將UITextField的文本與字符串進行比較?

當用戶輸入的字符串是正確的單詞的長度時,我想檢查該序列是否等於實際單詞。

If it is, I want to clear the text field and return "YES!". 

If it is not, I want to clear the text field completely so the user can try again. 

舉例:如果實際的詞是「邏輯」和用戶輸入「GOLIC」作爲他的猜測正確的話,我想文本字段完全清除,因此用戶可以再次嘗試。

 If the actual word is "LOGIC" and the user enters "LOGIC", I want the text field to clear and display the string "YES!" 

任何幫助非常感謝!

回答

1

UITextField有一個屬性「text」,您應該使用它。要與NSStrings進行比較,請使用isEqualToString方法。

if([myTextField.text isEqualToString:actualWord]) { 
    //display YES! 
} 
myTextField.text = @""; 

Btw。如果需要,可以使用UIAlertView來顯示YES:

UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"YES!" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 
[alertView show]; 
1

將此綁定到textField的editingDidEnd操作。

- (IBAction)testText:(id)sender 
{ 
    if ([myTextField.text isEqualToString:@"Logic"]) { 
     myTextField.text = @"Yes"; 
     UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"YES!" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; 
     [alertView show]; 
    } 
    else 
     myTextField.text = @""; 
} 
0

在文件(取決於你想要什麼樣的訪問權限,有超過該屬性)視圖中,向其中的UITextField屬於你應該增加:

@property (weak, nonatomic) IBOutlet UITextField *txtField; 

內:

@interface SettingsViewController() 

//Other code 

@end 

您還可以連接UITextField作爲故事板的插座:

  1. 按下Xcode左上角的西裝
  2. 從一側選擇故事板,從另一側選擇要從中訪問出口(屬性)的類。
  3. 按下控制按鈕並從UITextField拖動到該類中的接口塊。

這裏是一個鏈接: http://www.youtube.com/watch?feature=player_detailpage&v=xq-a7e_l_4I#t=120s

然後在你的代碼,你可以訪問它:

[self usernameField].text 

你還可以用一下:

if ([[self usernameField].text isEqualToString @"YOUR STRING"]) { 
//Code 
} else { 
//Code 
} 
相關問題