2012-10-30 71 views
1

我在我的viewController裏面有這個動畫縮小和滑動我的菜單。IOS動畫與ViewWillLayoutSubview

-(void)dismissMenuWithAnimation 
{ 
    CGRect originalFrame = self.view.frame; 
    [UIView animateWithDuration:2 
        animations:^{ 
         self.view.frame = CGRectMake(originalFrame.origin.x,originalFrame.origin.y+originalFrame.size.height,originalFrame.size.width,10); 
        } 
        completion:^(BOOL finished){ 
         [self.view removeFromSuperview]; 
         self.view.frame = originalFrame; 
        }]; 
} 

裏面同樣viewController,我重寫viewWillLayoutSubviews

-(void)viewWillLayoutSubviews 
{ 
    [super viewWillLayoutSubviews]; 

    CGRect viewBounds = self.view.bounds; 
    self.subView1.frame = CGRectMake(self.menuItemMidPosition,viewBounds.size.height-SUBVIEW1_HEIGHT,SUBVIEW1_WIDTH,SUBVIEW1_HEIGHT); 

} 

我有幾個子視圖,其框架設置在該viewWillLayoutSubviews方法。不在viewDidLoad中設置它,因爲框架仍然不正確。

問題是,當我關閉菜單時,首先調用動畫塊,並以某種方式立即將self.view.frame設置爲高度10.(縮小的幀)。當它到達viewWillLayoutSubviews時,邊界高度爲10.這會導致我的其他子視圖顯示不正確。

這似乎很愚蠢,但我不知道如何解決這個問題。有人可以幫忙嗎?謝謝。

+0

當你說「這會導致我的其他子視圖顯示不正確」時,你是什麼意思?他們有什麼不對? –

+0

另外,看起來您的視圖控制器的頂層視圖('self.view')是菜單。那是對的嗎?菜單視圖中的子視圖? –

+0

基本上我需要在viewWillLayoutSubview中獲取視圖框架,但是通過將框架設置爲動畫結束處的框架,動畫將框架搞亂。但要回答你的問題,self.view是菜單,菜單視圖中有子視圖。 – wjheng

回答

0

我自己的解決方案是根本不使用viewWillLayoutSubviews。我只是使用自動調整掩碼來確保框架正確調整大小。

+0

謝謝,我發現它在其生命週期的稍後階段也可以工作(它在viewWillLayoutSubviews被調用時起作用,但不會在調用viewWillAppear時起作用)。 – ragnarius

2

我剛碰到與作者相同的問題。雖然這個問題很老,但我會發布我的解決方案,希望有人像我一樣碰到這個問題。

解決方案是非常簡單的,完全類似於基於自動佈局動畫:

UIView.animate(
    withDuration: 0.2, 
    delay: 0, 
    options: .curveEaseInOut, 
    animations: { 
    // This will launch viewWillLayoutSubviews! 
    self.view.setNeedsLayout() 
    self.view.layoutIfNeeded() 
}, 
    completion: nil) 

和Objective-C版本:

[UIView animateWithDuration:0.2 
        delay:0 
        options:UIViewAnimationOptionCurveEaseInOut 
       animations:^{ 
       // This will launch viewWillLayoutSubviews! 
       [self.view setNeedsLayout]; 
       [self.view layoutIfNeeded]; 
       } 
       completion:nil]; 

我想即使我們有自動完全程序化的佈局佈局引擎在2017年。