Michael Michael - 1 year ago 398
iOS Question

How to add text field to inputAccessoryView and make the textView first responder

My code:

- (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 no work.

Another problem that delegate method to hide keyboard when ENTER is pressed does not work also.

- (BOOL) textFieldShouldReturn:(UITextField *)textField {

[textField resignFirstResponder];

return YES;

Tom Tom
Answer Source

I was facing the same challenge. Your (and my initial) approach probably don't work because the text field in the inputAccessoryView refuses to become first responder as the UITextField is not located on your screen initially.

My solution: check when the keyboard (and with that the accessory view) appear!

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

[[NSNotificationCenter defaultCenter] addObserver:self 

Step 2) When the keyboard has appeared, you can set the textfield in your inputAccessoryView to become first responder:

    [textField becomeFirstResponder];  // will return YES;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download