問(wèn)題:
當(dāng)有UIAlertViewat彈出后攻人,想要通過(guò)becomeFirstResponder使textfield定位光標(biāo)并調(diào)起鍵盤(pán)取试。
但事實(shí)是:只有光標(biāo)定位,并沒(méi)有喚起鍵盤(pán)怀吻。
原因:
UIAlertView彈窗過(guò)程中瞬浓,或者自定義的window初始化過(guò)程中,搶占了系統(tǒng)window成為keyWindow蓬坡。
解決辦法:
當(dāng)鍵盤(pán)消失后(稍微延時(shí)一下猿棉,防止鍵盤(pán)還沒(méi)有徹底消失),修改keyindow屑咳,之后再調(diào)用textfield的becomeFirstResponder方法萨赁。
搞定。
代碼如下:
//延時(shí)一下兆龙,等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);
}
//主要代碼:調(diào)整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調(diào)整后,喚起鍵盤(pán)
[self.textfield becomeFirstResponder];
});
代碼分析:
根據(jù)上述代碼,輔助的log打印如下:
(分別為修改keyWindow的前后變化)