我有一个带自定义视图类的ViewController。 我已经通过添加到viewWillAppear方法并删除viewDidDisappear中的通知来处理键盘通知。
通知添加到viewWillAppear:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector (keyboardWillShow:)
name: UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector (keyboardWillHide)
name: UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector (keyboardDidHide)
name: UIKeyboardDidHideNotification object:nil];
将通知移至viewDidDisappear:
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object: nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object: nil];
并从viewController的通知方法调用view方法。
问题:
如果我删除通知代码,那就完美了。
在iOS 7.0之前,它与通知代码完美配合。但是在iOS 7.0中,它不起作用。
我在每个通知方法中都打印了NSLog,在IOS 7.0中,keyboardWillShow方法最后执行并再次出现键盘。但是在iOS 6.0中,keyboardWillShow终于不会执行了。
我还实现了UITextFieldDelegate方法。
提前致谢
答案 0 :(得分:1)
下面你可以看到保留的键盘生命周期的差异(弹出后不会dealloc)推动viewController与textField / textView成为第一个响应者。
让我们按如下方式添加键盘观察器
- (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];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
}
- (void) viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardDidHideNotification object:nil];
}
iPhone 5的iOS6键盘生命周期
keyboardWillShow: keyboardFrame = {0,306,320,262}
[后退按钮]
viewDidDisappear:
[推送现有视图控制器]
iPhone 5的iOS7键盘生命周期
keyboardWillShow: keyboardFrame = {0,308,320,260}
[后退按钮]
viewDidDisappear:
[推送现有视图控制器]
不同之处在于iOS7正式尝试隐藏键盘弹出,但再次显示键盘。
因此,如果您想在两种情况下都隐藏键盘,则需要在 viewWillDisappear 中明确地重新设置textField。请注意 textField.isFirstResponder 等于 viewWillDisappear 中的 NO 但是
[textField resignFirstResponder];
解决了这个问题。