1

我正在为 iOS 的本地联系人应用程序创建一个类似于“新联系人”的表单。

我发现的唯一方法是创建一个表格视图并创建一个自定义表格视图单元格。

到目前为止,一切都很好...

现在,我的 TextField 只有在单击它时才会获得焦点,但是当我单击我创建的 Table View Cell 类的任何位置时,我想将焦点设置为 TextField。

我试过了:

- (void)setSelected:(BOOL)selected animated:(BOOL)animated
{
    [super setSelected:selected animated:animated];
    [self.txtInputer becomeFirstResponder];
    // Configure the view for the selected state
}

但它并没有像我希望的那样工作,焦点被设置到表格的最后一个字段。

4

1 回答 1

3

使用 UITextField 作为类的 .h(我称之为 textField)中的属性创建一个自定义单元格。(我称它为 TextFieldCell)

然后在 didSelectRowAtIndexPath 中有下面的代码。当一个单元格被点击时,您将获得对 TextFieldCells 的引用,然后您可以从中查找 textField 属性并在其上调用 becomeFirstResponder。注意我已经包含了你应该在这个例子中使用的枚举。如果您不知道这些是什么,请将它们放在您的#includes 下方并用谷歌搜索。喜欢枚举!!

//table view sections
enum
{
    TableViewSectionUsername = 0,
    TableViewSectionPassword,
        TableViewSectionLogin,
    TableViewSectionCount
};

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TextFieldCell *usernameCell = (TextFieldCell*)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:TableViewSectionUsername]];
    TextFieldCell *passwordCell = (TextFieldCell*)[_tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:TableViewSectionPassword]];

    //switch section
    switch(indexPath.section)
    {
        case TableViewSectionUsername:
        {
            [[usernameCell textField] becomeFirstResponder];
            break;
        }

        case TableViewSectionPassword:
        {
            [[passwordCell textField] becomeFirstResponder];
            break;
        }

        case TableViewSectionLogin:
        {
            if([[[usernameCell textField] text] isEqualToString:@""])
            {
                NSLog(@"Please enter a username");
                [[usernameCell textField] becomeFirstResponder];
                return;
            }

            if([[[passwordCell textField] text] isEqualToString:@""])
            {
                NSLog(@"Please enter a username");
                [[passwordCell textField] becomeFirstResponder];
                return;
            }

            [self dismissViewControllerAnimated:YES completion:nil];
            break;
        }

        default:
        {
        break;
        }
    }

    //deselect table cell
    [_tableView deselectRowAtIndexPath:indexPath animated:YES];

}

于 2013-04-12T07:26:48.697 回答