键盘管理

第一:在.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值