UITextField跟随键盘移动

利用通知监测键盘的移动,从而改变输入框的位置

-(void)dealloc

{

    [[NSNotificationCenter defaultCenter]removeObserver:self name:UIKeyboardWillChangeFrameNotification object:nil];

}


- (void)viewDidLoad

{

[super viewDidLoad];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];

}


#pragma mark - UIKeyboardNotification

- (void)keyboardWillChangeFrame:(NSNotification *)notification

{

    NSDictionary *userInfo = notification.userInfo;

    CGRect endFrame = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];

    CGRect beginFrame = [userInfo[UIKeyboardFrameBeginUserInfoKey] CGRectValue];

    CGFloat duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];

    UIViewAnimationCurve curve = [userInfo[UIKeyboardAnimationCurveUserInfoKey] integerValue];

    

    void(^animations)() = ^{

        [self willShowKeyboardFromFrame:beginFrame toFrame:endFrame];

    };

    

    void(^completion)(BOOL) = ^(BOOL finished){

    };

    

    [UIView animateWithDuration:duration delay:0.0f options:(curve << 16 | UIViewAnimationOptionBeginFromCurrentState) animations:animations completion:completion];

}


- (void)willShowKeyboardFromFrame:(CGRect)beginFrame toFrame:(CGRect)toFrame

{

    if (beginFrame.origin.y == [[UIScreen mainScreen] bounds].size.height){//将要移动的位置

        [UIView animateWithDuration:0.3 animations:^{

            _atextField.frame = RECTMAKE(0, CGRectGetHeight([self superview].frame)-CGRectGetHeight(self.frame)-toFrame.size.height+10, 320, 243);

        } completion:^(BOOL finished) {

        }];

    }else if (toFrame.origin.y == [[UIScreen mainScreen] bounds].size.height){//初始位置

        [UIView animateWithDuration:0.3 animations:^{

            _atextField.frame.frame = RECTMAKE(0, CGRectGetHeight([self superview].frame)-CGRectGetHeight(self.frame), 320, 243);

        }completion:^(BOOL finished) {

        }];

    }else{//将要移动的位置

        [UIView animateWithDuration:0.3 animations:^{

                _atextField.frame.frame = RECTMAKE(0, CGRectGetHeight([self superview].frame)-CGRectGetHeight(self.frame)-toFrame.size.height+10, 320, 243);

            } completion:^(BOOL finished) {

            }];

    }

}


你可能感兴趣的:(UITextField,iOSKeyboard,键盘检测)