IOS8下利用自动布局实现键盘的弹出效果

-(void)keyboardChange:(NSNotification*)notice
{
    NSValue *value = [[notice userInfo] objectForKey:@"UIKeyboardFrameEndUserInfoKey"];
    float keyEnd_y = [value CGRectValue].origin.y;
    float animationDuration = [[notice userInfo][@"UIKeyboardAnimationDurationUserInfoKey"] floatValue];
    
    CGRect frame = [[UIScreen mainScreen]bounds];//屏幕尺寸
    int SCREEN_WIDTH = frame.size.width;
    int SCREEN_HEIGHT = frame.size.height;
    
    if(!shouldResignFirstResponder){
        UIView *alphaCoverView = [[[UIApplication sharedApplication].delegate window] viewWithTag:10001];
        if (!alphaCoverView) {
            alphaCoverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, keyEnd_y - 40)];
            [alphaCoverView setBackgroundColor:[UIColor blackColor]];
            alphaCoverView.alpha = 0.0;
            alphaCoverView.tag = 10001;
            UITapGestureRecognizer *tapToResignirstResponder = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(textFielfWillResignFirstResponder)];
            [alphaCoverView addGestureRecognizer:tapToResignirstResponder];
            [[[UIApplication sharedApplication].delegate window] addSubview:alphaCoverView];
        }
        [UIView animateWithDuration:animationDuration animations:^{
            alphaCoverView.alpha = 0.4;
            alphaCoverView.frame = CGRectMake(0, 0, SCREEN_WIDTH, keyEnd_y - 40);//40是编辑框视图的高
        }];
    }
    float constant = 0.0;
    if (shouldResignFirstResponder) {
        //收回键盘时,将约束的值复原
        constant = SCREEN_HEIGHT - keyEnd_y;
        [UIView animateWithDuration:animationDuration animations:^{
            _m_spaceToBottom.constant = constant;
            [self.view layoutIfNeeded];
        }];
        shouldResignFirstResponder = NO;
    }else{
        constant = SCREEN_HEIGHT - keyEnd_y-46;//46是编辑框距离屏幕底部的距离
        [UIView animateWithDuration:animationDuration animations:^{
            _m_spaceToBottom.constant = constant;
            [self.view layoutIfNeeded];
        }];
    }
}
- (void)textFielfWillResignFirstResponder{
    UIView *view = [[[UIApplication sharedApplication].delegate window] viewWithTag:10001];
    [view removeFromSuperview];
    shouldResignFirstResponder = YES;
    [self.view endEditing:YES];
}


//键盘变化监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardChange:) name:@"UIKeyboardWillChangeFrameNotification" object:nil];

借鉴文章:

http://blog.csdn.net/u013016828/article/details/42102411

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值