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) {

            }];

    }

}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。