Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retrieve UITextField using tag

I have the following code:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (indexPath.row == 0)
        cell.tag = 0;
    else {
        cell.tag = 1;
    }

    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];

        UILabel *startDtLbl = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 80, 25)];
        if (indexPath.row == 0)
            startDtLbl.text = @"Username";
        else {
            startDtLbl.text = @"Password";
        }

        startDtLbl.backgroundColor = [UIColor clearColor];

        [cell.contentView addSubview:startDtLbl];

        UITextField *passwordTF = [[UITextField alloc] initWithFrame:CGRectMake(100, 5, 200, 35)];
        passwordTF.delegate = self;
        if (indexPath.row == 0)
            passwordTF.tag = 2;
        else {
            passwordTF.tag = 3;
        }
        [cell.contentView addSubview:passwordTF];
    }
    return cell;
}

I'd like to get the UITextField, how can I do that? I've tried the following and it failed:

UITableViewCell * username_cell = (UITableViewCell*)[self.view viewWithTag:0];
    UITableViewCell * password_cell = (UITableViewCell*)[self.view viewWithTag:1];

    UITextField * username = (UITextField*)[username_cell.contentView viewWithTag:2];
    UITextField * password = (UITextField*)[password_cell.contentView viewWithTag:3];
    NSLog(@"Username is %@", [username text]);
    NSLog(@"Password is %@", [password text]);
like image 248
aherlambang Avatar asked Jan 20 '23 10:01

aherlambang


1 Answers

You should stop to use tags to get cells. You should use indexPaths for this.

replace

UITableViewCell * username_cell = (UITableViewCell*)[self.view viewWithTag:0];
UITableViewCell * password_cell = (UITableViewCell*)[self.view viewWithTag:1];

with

NSIndexPath *indexPathUserName = [NSIndexPath indexPathForRow:0 inSection:0];
UITableViewCell * username_cell = [self.tableView cellForRowAtIndexPath:indexPathUserName];
NSIndexPath *indexPathPassword = [NSIndexPath indexPathForRow:1 inSection:0];
UITableViewCell * password_cell = [self.tableView cellForRowAtIndexPath:indexPathPassword];

and when you want to reference a specific view you can't use tag 0. Because all tags that don't have custom tags have a tag of 0. So if you use viewWithTag:0 you get the last added view. And usually that isn't the view you want.

like image 120
Matthias Bauch Avatar answered Jan 31 '23 08:01

Matthias Bauch