开发者

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

开发者 https://www.devze.com 2023-04-02 23:47 出处:网络
My code: - (void)viewDidLoad { [super viewDidLoad]; CGRect rectFake = CGRectZero; UITextField *fakeField = [[UITextField alloc] initWithFrame:rectFake];

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


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

精彩评论

暂无评论...
验证码 换一张
取 消