I tried to show a keyboard on after loading screen like this:
-(void) viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
UITextField *tf = [[UITextField alloc] initWithFrame:CGRectMake(10, 200, 300, 40)];
tf.borderStyle = UITextBorderStyleRoundedRect;
tf.text = @"test";
[self.view addSubview:tf];
if([tf canBecomeFirstResponder]){
[tf becomeFirstResponder]; // surely this line is called
}
}
This code works on ios 8,9,10 but not 11. I'm not sure why the keyboard isn't show automatically on ios 11 while text field is focusing (has cursor). And in this case, keyboard's notification isn't called:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
- (void) keyboardWillShow:(NSNotification *)note {
NSDictionary *userInfo = [note userInfo];
CGSize kbSize = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
DLog(@"Keyboard Height: %f Width: %f", kbSize.height, kbSize.width);
}
I even try this:
[tf performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0];
but still not work.
I have to click on text field to bring up the keyboard.
Is there anything update from Apple which I don't know?
Update: it looks like there is something wrong with my project or all my view controllers because I can't make the keyboard showing on all screens. But when I create new project with above code, it can work well. Here is one of the problem:
As you can see, I have to click on the textfield to show the keyboard, and from the second time, it can work properly. And this issue only happended on ios 11 (both simulator & device)
Here is the code for search field above:
UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 215, 30)];
textField.backgroundColor = [UIColor clearColor];
textField.placeholder = @"Enter text to search";
textField.borderStyle = UITextBorderStyleLine;
textField.layer.masksToBounds=YES;
textField.layer.borderColor=[[UIColor lightGrayColor]CGColor];
textField.layer.borderWidth= 1.0f;
textField.returnKeyType = UIReturnKeySearch;
textField.delegate = self;
textField.clearButtonMode = UITextFieldViewModeAlways;
[UIView transitionWithView:self.navigationController.navigationBar
duration:0.55f
options:UIViewAnimationOptionTransitionCrossDissolve
animations:^{
self.navigationItem.titleView = textField;
} completion:^(BOOL finished) {
[textField becomeFirstResponder];
}];
I wonder is there anything cause conflict keyboard?
When the TextField is not yet being drawn on the screen, then becomeFirstResponder() will not work. For example when it was hidden and never drawn. Then you need to call becomeFirstResponder() after it has been drawn. Maybe this will help:
DispatchQueue.main.async {
tf.becomeFirstResponder()
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With