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

邮差的信 提交于 2019-12-09 10:28:50

问题


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

回答1:


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 
                                         selector:@selector(changeFirstResponder)
                                             name:UIKeyboardDidShowNotification 
                                           object:nil];

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

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


来源:https://stackoverflow.com/questions/7334563/how-to-add-text-field-to-inputaccessoryview-and-make-the-textview-first-responde

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!