1

I can't figure out what is wrong here. Please see coments above NSLog function.

-(void)loadView
{
    ......    
    int x_position = 10;
    for (self.x = 0; self.x < 3; self.x++) 
    {
        self.textField = [[UITextField alloc] initWithFrame:CGRectMake(10, x_position, 300, 25)];
        self.textField.tag = self.x;
        // Output 0, 1, 2
        NSLog(@"%d", self.x);
        x_position += 40;

       [self.view addSubview:self.textField];
    }


    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [btn addTarget:self action:@selector(showNames) forControlEvents:UIControlEventTouchDown];
    [btn setTitle:@"Remove from view" forState:UIControlStateNormal];
    btn.frame = CGRectMake(0, x_position + 30, 210, 50);

    [self.view addSubview:btn];
    [self.textField release];
    [self.view release];
}

-(void)showNames
{
    while (self.x > 0) {
        self.x--;
        // output 2, 1, 0
        NSLog(@"%d", self.x);
        NSLog(@"%@", tmp);
    }
}

Here is console log

<UITextField: 0x4b39410; frame = (10 90; 300 25); text = 'Ad'; clipsToBounds = YES; opaque = NO; tag = 2; layer = <CALayer: 0x4b38c30>>
<UITextField: 0x4e22320; frame = (10 50; 300 25); text = 'Asd'; clipsToBounds = YES; opaque = NO; tag = 1; layer = <CALayer: 0x4e0a4c0>>
<UIView: 0x4b32330; frame = (0 20; 320 460); layer = <CALayer: 0x4b329a0>>

I expect object at tag 0 to be UITextField, not UIView. What is wrong here ?

1 Answer 1

3

Every view's tag defaults to zero, so your main UIView will have a tag of zero, and so will any other view where you didn't explicitly set the tag.

I suggest using an offset value for your tags, so you can make them all unique. For example:

#define TEXTFIELD_TAG_OFFSET 100

for (self.x = 0; self.x < 3; self.x++) 
{
    self.textField = [[UITextField alloc] initWithFrame:CGRectMake(10, x_position, 300, 25)];
    self.textField.tag = self.x + TEXTFIELD_TAG_OFFSET;
    // Output 0, 1, 2
    NSLog(@"%d", self.x);
    x_position += 40;

   [self.view addSubview:self.textField];
}

Now you can reference the Nth textfield with the tag number TEXTFIELD_TAG_OFFSET + N. That way your textfields will all have unique tags.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.