键盘防挡、收起键盘

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
-(void)keyboardWillShow:(NSNotification *)sender{
    CGRect frame=[[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    float duration=[[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSInteger curve=[[[sender userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    NSLog(@"show%@,duration%f,curve%ld",NSStringFromCGRect(frame),duration,curve);
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    UIView *firstResponder = [keyWindow performSelector:@selector(firstResponder)];
    if (![firstResponder isKindOfClass:[UITextField class]]){
        return;
    }
    CGRect rect=[firstResponder convertRect:firstResponder.bounds toView:self.view];
    float height=frame.size.height-(self.view.frame.size.height-(rect.origin.y+rect.size.height));
    if (height<0) {
        return;
    }
    [UIView animateWithDuration:duration animations:^{
        [self.view setFrame:CGRectMake(0, -height, self.view.frame.size.width, self.view.frame.size.height)];
    }];
}

-(void)keyboardWillHide:(NSNotification *)sender{
    CGRect frame=[[[sender userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    float duration=[[[sender userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    NSInteger curve=[[[sender userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
    NSLog(@"show%@,duration%f,curve%ld",NSStringFromCGRect(frame),duration,curve);
    [UIView animateWithDuration:duration animations:^{
        [self.view setFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    }];
}
//收起键盘
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    return [textField resignFirstResponder];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES]; //实现该方法是需要注意view需要是继承UIControl而来的
}

猜你喜欢

转载自blog.csdn.net/Draven__/article/details/104756395