如何将文本字段添加到inputAccessoryView并使textView第一响应者

我的代码:

- (void)viewDidLoad { [super viewDidLoad]; CGRect rectFake = CGRectZero; UITextField *fakeField = [[UITextField alloc] initWithFrame:rectFake]; [self.view addSubview:fakeField]; UIView *av = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 0.0, 39.0)]; av.backgroundColor = [UIColor darkGrayColor]; CGRect rect = CGRectMake(200.0, 4.0, 400.0, 31.0); UITextField *textField = [[UITextField alloc] initWithFrame:rect]; textField.borderStyle = UITextBorderStyleRoundedRect; textField.font = [UIFont systemFontOfSize:24.0]; textField.delegate = self; [av addSubview:textField]; fakeField.inputAccessoryView = av; [fakeField becomeFirstResponder]; } 

我试图添加

 [textField becomeFirstResponder] 

在最后,但它没有工作。

另一个问题,即按下ENTER键时隐藏键盘的方法也不起作用。

 - (BOOL) textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } 

我面临着同样的挑战。 您的(和我的初始)方法可能不工作,因为inputAccessoryView的文本字段拒绝成为第一响应者,因为UITextField最初不在屏幕上。

我的解决scheme:检查键盘(和附件视图)何时出现!

步骤1)收听通知(确保在收到通知之前执行此代码)。

 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeFirstResponder) name:UIKeyboardDidShowNotification object:nil]; 

步骤2)当键盘出现时,您可以将inputAccessoryView的文本字段设置为第一响应者:

 -(void)changeFirstResponder { [textField becomeFirstResponder]; // will return YES; }