user3418565
user3418565

Reputation: 1

How to get text from textfield tag in iPhone

I am creating text fields dynamically and each text field has tag.Now, I am trying to get text of textfield using that tags but, it returning UIButton and my application getting crashed.How can i get text from tags? please help me. Here is my code to get text :

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

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

my application is crashing at this line :

NSString *chkText = textValue.text;

and error is : -[UIButton text]: unrecognized selector sent to instance

Upvotes: 0

Views: 2023

Answers (5)

Hussain Shabbir
Hussain Shabbir

Reputation: 14995

The main problem is your view contains button as well. So when you are trying to access it. It is returning UIButton object. So it is always better that check the condition whether it is button type or textfield type object. Try below:-

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

Upvotes: 1

user2523320
user2523320

Reputation: 13

First check to which UIVIew you are adding this textfield as a subview.

Take that UIVIew instance and call viewWithTag method then your code works.

Upvotes: 0

Ryan
Ryan

Reputation: 4884

When you use tag, using NS_ENUM is a good habit.

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

Then you can use it.

[textField setTag:TAG_TEXT_INPUT];

Upvotes: 0

Yogendra
Yogendra

Reputation: 1716

Set textfield tag as any unique value like "346". (Avoid using 0 as tag value). And Use this --

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);
}

Upvotes: 0

Shamsudheen TK
Shamsudheen TK

Reputation: 31339

From your code (viewWithTag:textField.tag), If you can access your textField then why are you accessing it once more? However, the below description will help you

You have assigned the same tag to one of your UIButton control in the same view. Also make sure that textField.tag is greater than Zero.

The below code will fix the crash, however, it will not resolve your issue.

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");
}

Upvotes: 0

Related Questions