单个UITextField的应用程序在我保持键盘打开文本字段时会出现以下错误,并切换到另一个应用程序,同时在该应用程序中打开键盘。
错误:
Cannot snapshot view (<UIKeyboardImpl: 0x10040aa20; frame = (0 0; 414 226); layer = <CALayer: 0x174030d20>>) with afterScreenUpdates:NO, because the view is not in a window. Use afterScreenUpdates:YES.
以上错误会隐藏文本字段中的键盘。
这是我的代码
@implementation ViewController
BOOL isKeyboardOnScreen;
CGFloat currentKeyboardHeight;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeKeyboard)];
[tapRecognizer setNumberOfTapsRequired:1];
tapRecognizer.cancelsTouchesInView = YES;
[self.view addGestureRecognizer:tapRecognizer];
}
- (void)closeKeyboard {
[self.view endEditing:YES];
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillShow:)
name:UIKeyboardWillShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardWillHide:)
name:UIKeyboardWillHideNotification
object:nil];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}
#pragma mark - keyboard movements
- (void)keyboardWillShow:(NSNotification *)notification {
if (!isKeyboardOnScreen) {
isKeyboardOnScreen = YES;
CGSize keyboardSize = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;
if ([txtPhone isFirstResponder]) {
[UIView animateWithDuration:0.0 animations:^{
CGRect f = loginView.frame; //self.view.frame;
f.origin.y = f.origin.y-keyboardSize.height;
loginView.frame = f;
currentKeyboardHeight = keyboardSize.height;
}];
}
}
}
- (void)keyboardWillHide:(NSNotification *)notification {
if (isKeyboardOnScreen) {
isKeyboardOnScreen = NO;
if ([txtPhone isFirstResponder]) {
[UIView animateWithDuration:0.0 animations:^{
CGRect f = loginView.frame; //self.view.frame;
f.origin.y = f.origin.y+currentKeyboardHeight;
loginView.frame = f;
}];
}
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
我也尝试使用UIApplicationDidEnterBackgroundNotification,但没有工作。