键盘管理

来源:互联网 发布:sqlplus执行sql文件 -c 编辑:程序博客网 时间:2024/05/22 04:03
第一:在.h文件中加几个全局变量
    //键盘判断需要的变量    int first;    BOOL isRecoveryKeyboard;    int originY;
第二:在viewDidLoad方法中加上键盘的监听

    isRecoveryKeyboard=NO;    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];

第三:判断键盘是否挡住TextView

-(void)keyboardWillShow:(NSNotification *)notification{    if (self.textView.isFirstResponder) {        int height = self.textView.frame.origin.y+ self.textView.frame.size.height+10;        if (first==0) {            originY=self.view.frame.origin.y;            first=1;        }        height = IOS7_OR_LATER?height:height+20;        if ((KEYBOARD_HIGHT+height)>=WINDOW_HIGHT) {            isRecoveryKeyboard=YES;            [UIView animateWithDuration:0.25 animations:^{                [self.view setFrame:CGRectMake(self.view.frame.origin.x, originY+(WINDOW_HIGHT-(KEYBOARD_HIGHT+height)), self.view.frame.size.width, self.view.frame.size.height)];            } completion:^(BOOL finished) {            }];            [UIView commitAnimations];        }            }}-(void)keyboardWillHide:(NSNotification *)notification{    first=0;    if (!isRecoveryKeyboard) {        return;    }    isRecoveryKeyboard=NO;    [UIView animateWithDuration:0.25 animations:^{        [self.view setFrame:CGRectMake(self.view.frame.origin.x,originY, self.view.frame.size.width, self.view.frame.size.height)];    } completion:^(BOOL finished) {    }];    [UIView commitAnimations];}


不要忘了加上两个宏定义
#define WINDOW_HIGHT [UIApplication sharedApplication].keyWindow.frame.size.height#define KEYBOARD_HIGHT  [[[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height