0

I am trying to resize the UITextView when the keyboard is open.

in order to give my UITextView a new size ( so that it doesn't become shadowed by the keyboard) I make the following calculation

firstResult = UITextView bottom coordinate - keyboard top coordinate

firstResult should now have the size of the shadowed UITextView frame

then i do textView.frame.size.height -= firstResult which now should have a new size that would not be shadowed by the keyboard.

The problem with the code as it stands out is that there is always part of the UIView that is hidden behind the keyboard.

Could anyone point out what's wrong with my calculations so that the new size is always right? or any other way that I could use to resize the UITextView appropriately because all examples I find online do not work somehow.

the code

- (void)keyboardWasShown:(NSNotification *)notification {
CGRect viewFrame = input.frame;
    CGFloat textEndCord = CGRectGetMaxY(input.frame);
    CGFloat kbStartCord = input.frame.size.height - ([[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]).size.height;

    CGFloat result = fabsf( input.frame.size.height - fabsf( textEndCord - kbStartCord ));
    viewFrame.size.height -= result;
    NSLog(@"Original Height:%f, TextView End Cord: %f, KB Start Cord: %f, resutl: %f, the sum: %f",input.frame.size.height, textEndCord,kbStartCord,result,fabsf( textEndCord - kbStartCord ));
    input.frame = viewFrame;
}

4

1 回答 1

4

计算有问题,试试这个,

    - (void)keyboardWasShown:(NSNotification *)notification {
        CGRect viewFrame = input.frame;
        CGFloat textEndCord = CGRectGetMaxY(input.frame);
        CGFloat kbStartCord = textEndCord - ([[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue]).size.height;
        viewFrame.size.height = kbStartCord;
        input.frame = viewFrame;
    }

已编辑

通用公式也支持横向模式

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

    CGFloat keyboardHeight;
    CGRect viewFrame = textView.frame;
    CGFloat textMaxY = CGRectGetMaxY(textView.frame);
    if (UIInterfaceOrientationIsLandscape(self.interfaceOrientation)) {
        keyboardHeight = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.width;
    } else {
        keyboardHeight = [[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height;
    }
    CGFloat maxVisibleY = self.view.bounds.size.height - keyboardHeight;
    viewFrame.size.height = viewFrame.size.height - (textMaxY - maxVisibleY);
    textView.frame = viewFrame;
}

我必须添加UIInterfaceOrientationIsLandscape条件,因为[[[notification userInfo] objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size.height;当设备处于横向时不起作用。我知道这有点棘手,解决这个问题的另一种方法是检测设备旋转并更改参数值。它是由你决定。

公式说明

在此处输入图像描述

于 2013-09-05T17:29:46.243 回答