2012-07-27 241 views
0

我讓我的應用程序檢測到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

檢測方向並根據該信息決定移動視圖的方向。

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; 
+0

裏面的代碼我有viewFrame.origin.y - = animatedDistance;所以它應該提升視圖,因爲它確實當我在肖像,但在風景上,如果你看到我的意思(origin.y的行爲就像它是起源側道),橫向上,我不知道我是什麼缺少 – 2012-07-27 16:01:04

+0

這就是爲什麼我使用x以上 – Dustin 2012-07-27 16:01:39

+0

作品像一個魅力。 (爲了信息的緣故,我在文本框被辭職後不得不扭轉舉動。)謝謝你。 – 2012-07-27 17:32:59