我的应用程序的一个目标是管理多个自定义输入视图(来自 nib)以及常规系统键盘。一个或另一个将永远存在。(在示例代码中,我只管理一个笔尖 + 系统键盘)。
换出键盘时,我想保留您在系统键盘上看到的滑入/滑出效果。为了获得自定义键盘和系统键盘的滑动动画,我从文本字段中 resignFirstResponder 并等到键盘被隐藏。然后我执行 becomeFirstResponder 来引入新键盘。我使用 UIKeyboardDidHideNotification 作为触发器来触发 becomeFirstResponder 并加载新键盘。
我看到的问题是 UIKeyboardDidHideNotification 被触发了两次......执行 resignFirstResponder 时(如预期的那样)和执行 becomeFirstResponder 时再次触发。我怀疑我可以进入某种状态来检测第二个通知,但我想了解,为什么 becomeFirstResponder 导致它首先触发?
#import "DemoViewController.h"
@interface DemoViewController ()
@property (strong, nonatomic) IBOutlet UITextField *dummyTextField;
@end
@implementation DemoViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[[UITextField appearance] setKeyboardAppearance:UIKeyboardAppearanceDark];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
[self showNormalKeyboard];
[_dummyTextField becomeFirstResponder];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(void)keyboardDidHide:(NSNotification*) notification {
NSLog(@"Keyboard hidden: %@", notification);
// Executing this next line causes the notification to fire again
[_dummyTextField becomeFirstResponder];
}
-(void)showAlternateKeyboard{
_dummyTextField.inputView = [[[NSBundle mainBundle] loadNibNamed:@"AlternateKeyboardView" owner:self options:nil] lastObject];
[_dummyTextField resignFirstResponder];
}
-(void)showNormalKeyboard{
_dummyTextField.inputView = nil;
[_dummyTextField resignFirstResponder];
}
// This is a button on the DemoViewController screen
// that is always present.
- (IBAction)mainButtonPressed:(UIButton *)sender {
NSLog(@"Main Screen Button Pressed!");
}
// This is a button from the Custom Input View xib
// but hardwired directly into here
- (IBAction)alternateKeyboardButtonPressed:(UIButton *)sender {
NSLog(@"Alternate Keyboard Button Pressed!");
}
// This is a UISwitch on the DemoViewController storyboard
// that selects between the custom keyboard and the regular
// system keyboard
- (IBAction)keyboardSelectChanged:(UISwitch *)sender {
if (sender.on){
[self showAlternateKeyboard];
} else {
[self showNormalKeyboard];
}
}
@end