UITextField UITableViewCell子视图成为第一响应者?

Dan*_*ger 17 iphone cocoa-touch uitableview becomefirstresponder

我有一个核心数据应用程序,它使用导航控制器深入查看详细信息视图,然后如果您在详细信息视图中编辑其中一行数据,您将进入该单行的编辑视图,就像在Apples CoreDataBooks中一样示例(除了CoreDataBooks本身只使用一个UITextField,而不是UITableViewCell像我一样的子视图)!

编辑视图是以编程方式UITableviewController创建其单个部分单行和UITextfield单元格的表.

我想要发生的是当您选择要编辑的行并将编辑视图推入导航堆栈并且编辑视图在屏幕上移动时,我希望将文本字段选为firstResponder,以便键盘已经显示当视图在屏幕上移动以占据位置.就像在联系人应用程序或CoreDataBooks应用程序中一样.

我目前在我的应用程序中有以下代码导致视图加载,然后你看到键盘出现(这不是我想要的,我希望键盘已经在那里)

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [theTextField becomeFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)

你不能把它放进去,-viewWillAppear因为尚未创建文本字段,所以theTextField是零.在CoreDataBooks应用程序中,他们实现我想要的东西,他们从笔尖加载他们的视图,所以他们使用相同的代码,但在-viewWillAppear文本字段已经创建!

无论如何在没有创建笔尖的情况下解决这个问题,我希望保持实现编程以实现更大的灵活性.

非常感谢

Dan*_*ger 15

在与Apple Dev支持团队交谈后,我得到了答案!

你需要做的是创建一个离屏UITextField-(void)loadView;,然后将其设置为第一个响应者则对viewDidLoad方法,你可以设置UITextFieldUITableViewCell成为第一个响应者.下面是一些示例代码(记住我正在这样做,UITableViewController所以我也在创建tableview!

- (void)loadView
{
    [super loadView];

    //Set the view up.
    UIView *theView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.view = theView;
    [theView release];

    //Create an negatively sized or offscreen textfield
    UITextField *hiddenField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, -10, -10)];
    hiddenTextField = hiddenField;
    [self.view addSubview:hiddenTextField];
    [hiddenField release];

    //Create the tableview
    UITableView *theTableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds] style:UITableViewStyleGrouped];
    theTableView.delegate = self;
    theTableView.dataSource = self;
    [self.view addSubview:theTableView];
    [theTableView release];

    //Set the hiddenTextField to become first responder
    [hiddenTextField becomeFirstResponder];

    //Background for a grouped tableview
    self.view.backgroundColor = [UIColor groupTableViewBackgroundColor];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    //Now the the UITableViewCells UITextField has loaded you can set that as first responder
    [theTextField becomeFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)

我希望这有助于任何与我保持同一位置的人!

如果其他人能够看到更好的方法来做到这一点,请说.

  • 我和这个人争斗了一年多.有时我会得到一个可行的解决方案,但是iOS的新更新会破坏它.很烦人.这是迄今为止我见过的最好的解决方案,尽管感觉有多酷. (3认同)

Den*_*ong 5

尝试在viewDidAppear方法中执行此操作,适合我.