美文网首页iOS 技巧
iOS调用becomeFirstResponder失效,无法弹出

iOS调用becomeFirstResponder失效,无法弹出

作者: 艾欧尼亚 | 来源:发表于2020-08-18 11:47 被阅读0次

问题:

当有UIAlertViewat弹出后,想要通过becomeFirstResponder使textfield定位光标并调起键盘。

但事实是:只有光标定位,并没有唤起键盘。

原因:

UIAlertView弹窗过程中,或者自定义的window初始化过程中,抢占了系统window成为keyWindow。

解决办法:

当键盘消失后(稍微延时一下,防止键盘还没有彻底消失),修改keyindow,之后再调用textfield的becomeFirstResponder方法。

搞定。

代码如下:

                //延时一下,等alert完全消失,再修改keywindow
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
 
            NSLog(@"before:\n");
            for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
                NSLog(@"isKeyWindow = %d window level = %.1f frame = %@ class = %@\n",
                      window.isKeyWindow, window.windowLevel,
                      NSStringFromCGRect(window.frame), window.class.description);
                
            }
            
            //主要代码:调整keywindow
            for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
                if(CGSizeEqualToSize([UIScreen mainScreen].bounds.size, window.frame.size)&&window.windowLevel==0.0 && !window.isKeyWindow){
                    [window makeKeyAndVisible];
                    break;
                }
            }
            
            NSLog(@"after:\n");
            for (UIWindow *window in [[UIApplication sharedApplication] windows]) {
                NSLog(@"isKeyWindow = %d window level = %.1f frame = %@ class = %@\n",
                      window.isKeyWindow, window.windowLevel,
                      NSStringFromCGRect(window.frame), window.class.description);
                
            }
 
            
            //keywindow调整后,唤起键盘
            [self.textfield becomeFirstResponder];
 
        });

代码分析:

根据上述代码,辅助的log打印如下:
(分别为修改keyWindow的前后变化)


image

转自

相关文章

网友评论

    本文标题:iOS调用becomeFirstResponder失效,无法弹出

    本文链接:https://www.haomeiwen.com/subject/vqihjktx.html