鍵盤防擋、收起鍵盤

[[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而來的
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章