R4j*_*R4j 5 keyboard objective-c ios
我尝试在加载屏幕后显示键盘,如下所示:
-(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
}
}
Run Code Online (Sandbox Code Playgroud)
此代码适用于 ios 8,9,10 但不适用于 11。我不确定为什么当文本字段聚焦(有光标)时,键盘不会在 ios 11 上自动显示。在这种情况下,不会调用键盘的通知:
[[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);
}
Run Code Online (Sandbox Code Playgroud)
我什至尝试这个:
[tf performSelector:@selector(becomeFirstResponder) withObject:nil afterDelay:0];
Run Code Online (Sandbox Code Playgroud)
但还是不行。
我必须单击文本字段才能调出键盘。
苹果有什么我不知道的更新吗?
更新:看起来我的项目或我的所有视图控制器都有问题,因为我无法让键盘显示在所有屏幕上。但是当我用上面的代码创建新项目时,它可以很好地工作。这是问题之一:
如您所见,我必须单击文本字段才能显示键盘,从第二次开始,它就可以正常工作了。而这个问题只发生在 ios 11(模拟器和设备)
下面是上面搜索字段的代码:
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];
}];
Run Code Online (Sandbox Code Playgroud)
我想知道有什么原因导致键盘冲突吗?
当 TextField 尚未在屏幕上绘制时, becomeFirstResponder() 将不起作用。例如,当它被隐藏并且从未绘制时。然后您需要在绘制后调用 becomeFirstResponder() 。也许这会有所帮助:
DispatchQueue.main.async {
tf.becomeFirstResponder()
}
Run Code Online (Sandbox Code Playgroud)