动画虚拟键盘

时间:2012-07-27 15:41:10

标签: iphone objective-c xcode ipad

我让我的应用程序检测到iPad上的方向,并相应地重新调整它的位置位置,以便在纵向和横向上运行良好。

我在虚拟键盘方法中的问题是我没有考虑方向:在用户点击其中一个文本框时,该方法将提升视图以为键盘腾出空间并使文本框可见(不是但是当用户处于横向状态并点按文本框时,动画会将视图推向侧面而不是向上,就像它仍处于纵向状态一样。 (如果我将iPad颠倒过来,它会将我的视图框向下推而不是向上)

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    CGRect textFieldRect = [self.view.window convertRect:textField.bounds fromView:textField];

    CGRect viewRect = [self.view.window convertRect:self.view.bounds fromView:self.view];
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator = midline - viewRect.origin.y - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator = (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION) * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    if (heightFraction < 0.0)  {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)   {
        heightFraction = 1.0;
    }

    UIInterfaceOrientation orientation =[[UIApplication sharedApplication] statusBarOrientation];

    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)   {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    // viewFrame.origin.x -= animatedDistance;


    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    [self.view setFrame:viewFrame];
    [UIView commitAnimations];
}

我也有:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
} 

当设备更改方向时,如何更改方法以使其正确设置动画?

由于

1 个答案:

答案 0 :(得分:1)

检测方向并根据该信息决定移动视图的方向。

if ([UIDevice currentDevice].orientation==UIDeviceOrientationLandscapeLeft)
    viewFrame.origin.x -= animatedDistance;
if ([UIDevice currentDevice].orientation==UIDeviceOrientationLandscapeRight)
    viewFrame.origin.x += animatedDistance;
if ([UIDevice currentDevice].orientation==UIDeviceOrientationPortrait)
    viewFrame.origin.y -= animatedDistance;
if ([UIDevice currentDevice].orientation==UIDeviceOrientationPortraitUpsideDown)
    viewFrame.origin.y += animatedDistance;