Search code examples
iosuitextviewuitextviewdelegate

iPhone: textViewdDidBeginEditing: textview.tag always 0


In my application, I've written a cycle to assign tag to my textviews:

for(j = 0; j<9; j++)
    for(k = 0; k<9; k++) {
        UITextView*txtview =
        [[UITextView alloc]initWithFrame:CGRectMake(x,y,25,25)];
        txtview.backgroundColor = [UIColor clearColor];
        txtview.textColor = [UIColor redColor];
        txtview.font = [UIFont fontWithName:@"TrebuchetMS-Bold" size:18];
        txtview.tag = 10*k + j;
        txtview.keyboardType = UIKeyboardTypeNumberPad;
        [self.view addSubview:txtview];
        [txtview sizeToFit];
        txtview.delegate = self;
        x = x+40;
        y = y+40;
        NSLog(@"%d",txtview.tag);
    }

}

The log at the end of the cycle print properly the just assigned tag.

The problem is that when the method textViewDidBeginEditing is called, if I try to retrieve the textView.tag with another log, it always returns 0. How can I solve this?

Thank you in advance.


Solution

  • Other than adding the UITapGestureRecognizer, you can set a delgate for UITextView.

    Code to do that is as follows.

    txtview.delegate = self;

    Now you can listen to the delegate method.

    
    - (void)textViewDidBeginEditing:(UITextView *)textView
    {
       NSLog(@"textView tag is %d",txtview.tag);
    }