如何从iPhone中的textfield标签获取文本

时间:2014-07-11 06:00:51

标签: ios iphone objective-c uitextfield

我正在动态创建文本字段,每个文本字段都有tag.Now,我正在尝试使用该标签获取文本字段的文本但是,它返回UIButton并且我的应用程序崩溃。如何从标签获取文本?请帮我。 这是我获取文本的代码:

UITextField *textValue = (UITextField *)[self.view viewWithTag:textField.tag];
NSString *chkText = textValue.text;

NSLog(@"entered Text %@",chkText);

我的应用程序崩溃在这一行:

NSString *chkText = textValue.text;

并且错误是:      - [UIButton text]:无法识别的选择器发送到实例

5 个答案:

答案 0 :(得分:1)

主要问题是你的视图包含按钮。所以当你试图访问它时。它正在返回UIButton对象。因此,检查条件是按钮类型还是文本字段类型对象总是更好。请尝试以下方法: -

id nextTextField = [self.view viewWithTag:textField.tag];
nextTextField=([nextTextField isKindOfClass:[UITextField class]]) ? nextTextField.text : nextTextField.title;
NSLog(@"%@", nextTextField);

答案 1 :(得分:0)

将textfield标记设置为任何唯一值,例如" 346"。 (避免使用0作为标记值)。并使用此 -

UITextField *textValue = nil; 
id myObj = [self.view viewWithTag:yourTagValue];
if([myObj isKindOfClass:[UITextField class]])
{
   textValue = (UITextField*)myObj; 
   NSString *chkText = textValue.text;
   NSLog(@"entered Text %@",chkText);
}

答案 2 :(得分:0)

从您的代码(viewWithTag:textField.tag),如果您可以访问textField,那么为什么还要再次访问它?但是,以下说明将对您有所帮助

您已在同一视图中将相同的标记分配给您的某个UIButton控件。另外,请确保textField.tag 大于零

以下代码将修复崩溃,但是,它无法解决您的问题。

UITextField *textFeild = [[self.view viewWithTag:textFieldTag] isKindOfClass:[UITextField class]]?(UITextField *)[self.view viewWithTag:textFieldTag]:nil;

if(nil != textFeild)
{
   NSString *chkText = textFeild.text;
   NSLog(@"entered Text %@",chkText);
}
else
{
  NSLog(@"textFeild is null");
}

答案 3 :(得分:0)

当你使用标签时,使用NS_ENUM是一个好习惯。

NS_ENUM(NSUInteger, TEST_TAGS)
{
    TAG_TEXT_INPUT,
    TAG_BTN_GO,
};

然后你可以使用它。

[textField setTag:TAG_TEXT_INPUT];

答案 4 :(得分:0)

首先检查您要将此文本字段添加为子视图。

获取该UIVIew实例并调用viewWithTag方法,然后您的代码可以运行。