iOS 文字輸入框隨鍵盤上移

ladeng發表於2014-11-03

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



相關文章