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]);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With