2013-05-10 229 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 
} 
相关问题