5

当键盘显示时,我正在尝试调整 UITextView 的大小。在 iPhone 上它运行良好。当系统发送键盘通知时,文本视图会调整大小。完成编辑后,我调整它的大小以填充初始空间。(是的,我假设编辑停止时键盘消失了。我应该改变它。但是,我不认为这是我的问题。)

当我在 iPad 上调整 textview 的大小时,框架会正确调整大小,但应用程序似乎将框架的 Y 值重置为零。这是我的代码:

- (void) keyboardDidShowWithNotification:(NSNotification *)aNotification{

//
//  If the content view being edited
//  then show shrink it to fit above the keyboard.
//

if ([self.contentTextView isFirstResponder]) {

    //
    //  Grab the keyboard size "meta data"
    //

    NSDictionary *info = [aNotification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size;

    //
    //  Calculate the amount of the view that the keyboard hides.
    //
    //  Here we do some confusing math voodoo.
    //
    //  Get the bottom of the screen, subtract that 
    //  from the keyboard height, then take the 
    //  difference and set that as the bottom inset 
    //  of the content text view.
    //

    float screenHeightMinusBottom = self.contentTextView.frame.size.height + self.contentTextView.frame.origin.y;

    float heightOfBottom = self.view.frame.size.height - screenHeightMinusBottom;


    float insetAmount = kbSize.height - heightOfBottom;

    //
    //  Don't stretch the text to reach the keyboard if it's shorter.
    //

    if (insetAmount < 0) {
        return;
    }

    self.keyboardOverlapPortrait = insetAmount;

    float initialOriginX = self.contentTextView.frame.origin.x;
    float initialOriginY = self.contentTextView.frame.origin.y;

    [self.contentTextView setFrame:CGRectMake(initialOriginX, initialOriginY, self.contentTextView.frame.size.width, self.contentTextView.frame.size.height-insetAmount)];


}

为什么这可以在 iPhone 上运行,而不是在 iPad 上运行?另外,我的自动调整大小蒙版会做出意想不到的改变吗?

4

1 回答 1

3

就像@bandejapaisa 所说的那样,我发现方向是一个问题,至少在我的测试中是这样。

第一件事是关于kbSize.height误导的使用,因为在横向方向它代表键盘的宽度。因此,由于您的代码在 a 中,UIViewController您可以这样使用它:

float insetAmount = (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)?kbSize.height:kbSize.width) - heightOfBottom;

给出接口的self.interfaceOrientation方向(可以与设备方向不同),如果给定的方向是纵向(顶部或底部) ,则宏UIInterfaceOrientationIsPortrait返回。YES所以由于键盘高度是在kbSize.height界面为Portrait时,而在kbSize.width界面为Landscape时,我们只需要测试方向即可获得好的值。

但这还不够,因为我发现了同样的self.view.frame.size.height价值问题。所以我使用了相同的解决方法:

float heightOfBottom = (UIInterfaceOrientationIsPortrait(self.interfaceOrientation)?self.view.frame.size.height:self.view.frame.size.width) - screenHeightMinusBottom;

希望这可以帮助...

于 2011-09-21T14:09:26.473 回答