iphone - UITableViewCell 的 UITextField subview 成为第一响应者?

标签 iphone cocoa-touch uitableview becomefirstresponder

我有一个核心数据应用程序,它使用导航 Controller 深入到详细 View ,然后如果您编辑详细 View 中的一行数据,您将进入该行的编辑 View ,例如在苹果的 CoreDataBooks 示例中(除了 CoreDataBooks 只使用自己的 UITextField ,而不是像我一样是 UITableViewCell 的 subview )!

编辑 View 是一个 UITableviewController,它以编程方式在单元格中创建包含单节单行和 UITextfield 的表格。

我想要发生的是,当您选择要编辑的行并且编辑 View 被推送到导航堆栈上并且编辑 View 以动画方式在屏幕上移动时,我希望将文本字段选择为firstResponder,以便键盘当 View 在屏幕上移动以就位时,已经显示了。就像在通讯录应用程序或 CoreDataBooks 应用程序中一样。

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

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [theTextField becomeFirstResponder];
}

您不能将其放入 -viewWillAppear 中,因为文本字段尚未创建,因此 theTextField 为零。在 CoreDataBooks 应用程序中,他们实现了我想要的目标,他们从 Nib 加载 View ,因此他们使用相同的代码,但在 -viewWillAppear 中,因为文本字段已经创建!

有没有办法在不创建 Nib 的情况下解决这个问题,我想保持实现编程化以实现更大的灵 active 。

非常感谢

最佳答案

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

您需要做的是在 -(void)loadView; 中创建一个离屏 UITextField ,然后将其设置为第一响应者,然后在 viewDidLoad 方法,您可以将 UITableViewCell 中的 UITextField 设置为第一响应者。下面是一些示例代码(请记住,我是在 UITableViewController 中执行此操作,因此我也创建了表格 View !

- (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];
}

我希望这可以帮助任何与我处于相同位置的人!

如果其他人能找到更好的方法,请说出来。

关于iphone - UITableViewCell 的 UITextField subview 成为第一响应者?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2658261/

相关文章:

iphone - 如何设置 UIAlertView 的高度和宽度?

ios - UIScrollView setContentSize 不起作用

iphone - 如何更改导航栏高度

iphone - 使用 NSURLConnection 缓存和查询 HTTP header 的问题

iphone - 设备运动更新的实际频率低于预期,但会随着设置而增加

uitableview - 带有标签和 UISlider 的自定义 UITableViewCell 在 ios 7 的 6 次崩溃中运行良好。 ?? UITableViewCellScrollView?

iphone - 尝试强制重绘 UITableViewCell

ios - UITableView 滚动条没有拉伸(stretch)

ios - 以编程方式定义和执行 segue

ios - 如何从日历中获取所有事件(Swift)