iOS 文本输入框随键盘上移

iPhone开发时,键盘弹出来后可能会盖住输入框,这个问题是需要自己解决的,不像android系统解决了,很久没写了,发现一个哥们写的还不错,转一下:

- (void)keyboardWillShow:(NSNotification *)notification {

    NSDictionary *userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];

    CGRect keyboardRect = [aValue CGRectValue];
    keyboardRect = [self.view convertRect:keyboardRect fromView:nil];

    // 根据老的 frame 设定新的 frame
    CGRect newTextViewFrame = _inputTextView.frame; // by michael
    newTextViewFrame.origin.y = keyboardRect.origin.y - _inputTextView.frame.size.height;

    // 键盘的动画时间,设定与其完全保持一致
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];

    // 键盘的动画是变速的,设定与其完全保持一致
    NSValue *animationCurveObject = [userInfo valueForKey:UIKeyboardAnimationCurveUserInfoKey];
    NSUInteger animationCurve;
    [animationCurveObject getValue:&animationCurve];

    // 开始及执行动画    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:(UIViewAnimationCurve)animationCurve];    
    _inputTextView.frame = newTextViewFrame;
    [UIView commitAnimations];
}

键盘消失时的处理,文本输入框回到页面底部。

- (void)keyboardWillHide:(NSNotification *)notification {

    NSDictionary* userInfo = [notification userInfo];

    // 键盘的动画时间,设定与其完全保持一致
    NSValue *animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];

    // 键盘的动画是变速的,设定与其完全保持一致
    NSValue *animationCurveObject =[userInfo valueForKey:UIKeyboardAnimationCurveUserInfoKey];
    NSUInteger animationCurve;
    [animationCurveObject getValue:&animationCurve];

    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:animationDuration];
    [UIView setAnimationCurve:(UIViewAnimationCurve)animationCurve];
    CGRect newTextViewFrame = _inputTextView.frame;
    newTextViewFrame.origin.y = DEVICE_HEIGHT - _inputTextView.frame.size.height;
    _inputTextView.frame = newTextViewFrame;
    [UIView commitAnimations];
}
主要是根据键盘的高度来收缩界面的内容,重置输入区域的frame。

转自:http://blog.csdn.net/prevention



你可能感兴趣的:(iOS 文本输入框随键盘上移)