How to add a text field to inputAccessoryView and make textview the first responder

My code is:

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

I tried to add

 [textField becomeFirstResponder] 

at the end, but it does not work.

Another problem is that the delegate method of hiding the keyboard when pressing ENTER does not work.

 - (BOOL) textFieldShouldReturn:(UITextField *)textField { [textField resignFirstResponder]; return YES; } 
+7
source share
1 answer

I faced the same challenge. Your (and my original) approach probably doesn't work, because the text field in inputAccessoryView refuses to become the first responder, since UITextField not on your screen initially.

My solution: check when the keyboard appears (and with this kind of accessory).

Step 1) Listen to the notification (make sure that this code is executed before you want to receive the notification).

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

Step 2) When the keyboard appears, you can set the text box in your inputAccessoryView to become the first responder:

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

All Articles