iphone - 使用标签检索 UITextField

标签 iphone objective-c ios

我有以下代码:

- (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/

相关文章:

objective-c - 触发事件的全局监视器后,如何在聚焦的 NSTextfield(在我的应用程序之外)上写入?

ios - iOS 中的 JS getTimezoneOffset()

objective-c - 如何将核心数据添加到现有的基于选项卡的 IOS 项目

ios - ABAddressBookCopyArrayOfAllPeople 不返回任何人

iphone - 错误 CGImageCreate : invalid image size: 0 x 0 with a (picker) window rotation

iphone - APN 设备 token 对于每个单独的应用程序来说都是唯一的吗?

php - 如何向使用 iPhone 的用户显示特殊的页面叠加层?

iOS 9、iPhone 6S plus、 Metal 、无法链接到功能 frexp

ios - 在 iOS 10 上使用 Facebook SDK 登录时出现空白页面

Webapp 上的 iPhone 键盘布局