Search code examples
uiviewtagstextfieldnstextfield

How to call a tagged textfield


I am creating a series of textfields programmatically using tags. I want to be able to access the data in each text field, but it keeps reverting back to the last tag.

In this example I am creating 10 textfields. When you click on a field it should turn that field blue, but it always turns the last field blue.

How do I access the field tags so I can get to the correct textfield?

I added NSlog to test the sender #.

@implementation ViewController
@synthesize name = _name ;
- (void)viewDidLoad
{
    [super viewDidLoad];
    int y = 20 ;
    for(int i=1; i <= 10; i++)
    {
      CGRect frame = CGRectMake(20, y, 100, 30 ) ;
      name = [[UITextField alloc] initWithFrame:frame];
      [name setTag:i] ;
      [name setBackgroundColor:[UIColor whiteColor]] ;
      [name addTarget:self action:@selector(makeBlue:) forControlEvents:UIControlEventTouchDown];
      [self.view addSubview:name];
      y += 38;
    }
}

- (void)makeBlue:(id)sender
{
    int i = (int)[sender tag] ;
    [name setTag:i] ;
    NSLog(@"%d", i);
    [name setBackgroundColor:[UIColor blueColor]] ;
}

EDIT: That is great. Thank you. It certainly solved one of my problems. I guess I was expecting a different answer that would lead me in a direction to solve my second problem. I want to take the input from a tagged textfield to use it elsewhere. I have the same problem that I am only getting the input from the last textfield.

- (void)viewDidLoad
{
[super viewDidLoad];

int y = 20 ;
for(int tag=1; tag <= 10; tag++)
{
    CGRect frame = CGRectMake(20, y, 100, 30 ) ;
    name = [[UITextField alloc] initWithFrame:frame];
    [name setTag:tag] ;
    [name setBackgroundColor:[UIColor whiteColor]] ;
    [name addTarget:self action:@selector(makeItSo:) forControlEvents:UIControlEventEditingDidEnd];
    [self.view addSubview:name];
    [name setDelegate:self] ;
    y += 38;
}
}

- (void)makeItSo:(id)sender
{
int tag = (int)[sender tag] ;
[name setTag:tag] ;
NSString * aName = [name text] ;
NSLog(@"%@", aName) ;
}

In this example I don't need to use setTag again in the makeItSo method, but I don't know how to get the value from a particular tag.


Solution

  • In your makeBlue: method you are just re-assigning a tag for no reason. This doesn't change the view. The variable name will point to the last view created in the loop even if you change its tag. If you want to access the views by tag use :

    [self.view viewWithTag:<tag>]
    

    So your makeBlue: code will look like:

    - (void)makeBlue:(id)sender
    {
        int tag = (int)[sender tag] ;
        UIView *tagView = [self.view viewWithTag:tag]
        [tagView setBackgroundColor:[UIColor blueColor]] ;
    }
    

    So for taking the value of a text field you would use:

     name = [self.view viewWithTag:[sender tag]];
     NSString *fieldText = name.text;