想在键盘上添加一个按钮,实时根据键盘不同高度变换按钮位置,再不做输入的时候点击按钮能够隐藏键盘,这种方式在很多软件上都有体现,然后在网上查阅了关于检测键盘高度一些相关知识,以下是一个Demo,代码有很多需要优化地方,仅供需要者参考;
- (void)viewDidLoad { NSLog(@"%@",NSStringFromSelector(_cmd)); [super viewDidLoad]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardWillShowNotification object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil]; }
- (void)handleKeyboardDidShow:(NSNotification *)notification { NSLog(@"%@",NSStringFromSelector(_cmd)); NSDictionary *info = [notification userInfo]; CGRect keyboardFrame; [[info objectForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame]; CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey]CGRectValue].size; CGFloat distanceToMove = kbSize.height; NSLog(@"---->动态键盘高度:%f",distanceToMove); if (exitButton == nil) { exitButton = [UIButton buttonWithType:UIButtonTypeRoundedRect]; CGRect exitBtFrame = CGRectMake(self.view.frame.size.width-40, self.view.frame.size.height - distanceToMove, 40.0f, 30.0f); exitButton.frame = exitBtFrame; [exitButton setImage:[UIImage imageNamed:@"DoneDown.png"] forState:UIControlStateNormal]; [self.view addSubview:exitButton]; } exitButton.hidden=NO; [self adjustPanelsWithKeyBordHeight:distanceToMove]; [exitButton addTarget:self action:@selector(CancelBackKeyboard:) forControlEvents:UIControlEventTouchDown]; }
在这一段代码上,后面注释了5行,因为打算当键盘推出的时候,按钮从视图上移除,或者释放按钮,但是都导致了应用程序崩溃,后来就没有释放和移除操作了
- (void)handleKeyboardWillHide:(NSNotification *)notification { NSLog(@"%@",NSStringFromSelector(_cmd)); if (exitButton.hidden==NO) { exitButton.hidden = YES; } // if (exitButton.superview) // { // [exitButton removeFromSuperview]; // [exitButton release]; // } }
-(void)adjustPanelsWithKeyBordHeight:(float) height { NSLog(@"%@",NSStringFromSelector(_cmd)); if (exitButton) { CGRect exitBtFrame = CGRectMake(self.view.frame.size.width - 40, self.view.frame.size.height - height-30, 40.0f, 30.0f); exitButton.frame = exitBtFrame; [self.view addSubview:exitButton]; } // UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1]; // if (exitButton.superview == nil) // { // [tempWindow addSubview:exitButton]; // // 注意这里直接加到window上 // } }
-(void)CancelBackKeyboard:(id)sender { NSLog(@"%@",NSStringFromSelector(_cmd)); [textField resignFirstResponder]; } - (void)viewDidUnload { [self setTextField:nil]; exitButton=nil; [super viewDidUnload]; // Release any retained subviews of the main view. } - (void)dealloc { [textField release]; [exitButton release]; [[NSNotificationCenter defaultCenter] removeObserver:self];//移除所注册的通知 [super dealloc]; }