我有以下代码:
- (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;
}
我想获取 UITextField,我该怎么做?我尝试了以下但失败了:
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]);
最佳答案
您应该停止使用标签来获取单元格。您应该为此使用 indexPaths。
替换
UITableViewCell * username_cell = (UITableViewCell*)[self.view viewWithTag:0];
UITableViewCell * password_cell = (UITableViewCell*)[self.view viewWithTag:1];
与
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];
当你想引用一个特定的 View 时,你不能使用标签 0。因为所有没有自定义标签的标签都有一个标签 0。所以如果你使用 viewWithTag:0,你会得到最后添加的 View 。通常这不是您想要的 View 。
关于iphone - 使用标签检索 UITextField,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5063408/