2011-07-07 38 views
3

我有一個奇怪的錯誤,我似乎無法弄清楚。我創建了一個閃亮的動畫,它完美的工作,但由於某種原因,當我通過UINavigationController或UITabView導航到另一個視圖時(奇怪的是模態視圖不會影響它)停止。任何想法爲什麼,以及如何確保動畫不會停止?使用UINavigationController或UITabView時動畫停止

UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)]; 
[whiteView setBackgroundColor:[UIColor whiteColor]]; 
[whiteView setUserInteractionEnabled:NO]; 
[self.view addSubview:whiteView]; 

CALayer *maskLayer = [CALayer layer]; 

maskLayer.backgroundColor = [[UIColor colorWithRed:1.0f green:1.0f blue:1.0f alpha:0.0f] CGColor]; 
maskLayer.contents = (id)[[UIImage imageNamed:@"ShineMask.png"] CGImage]; 

// Center the mask image on twice the width of the text layer, so it starts to the left 
// of the text layer and moves to its right when we translate it by width. 
maskLayer.contentsGravity = kCAGravityCenter; 
maskLayer.frame = CGRectMake(-whiteView.frame.size.width, 
          0.0f, 
          whiteView.frame.size.width * 2, 
          whiteView.frame.size.height); 

// Animate the mask layer's horizontal position 
CABasicAnimation *maskAnim = [CABasicAnimation animationWithKeyPath:@"position.x"]; 
maskAnim.byValue = [NSNumber numberWithFloat:self.view.frame.size.width * 9]; 
maskAnim.repeatCount = HUGE_VALF; 
maskAnim.duration = 3.0f; 
[maskLayer addAnimation:maskAnim forKey:@"shineAnim"]; 

whiteView.layer.mask = maskLayer; 
+0

什麼方法執行這個代碼? – cduhn

+0

此代碼是自定義UIViewController對象的一部分。該對象在另一個視圖中被初始化,並從該視圖調用該方法。 – Rob

回答

0

你maskAnim由maskLayer,這是由whiteView的層,這是由whiteView保持,這是由self.view保留保留保留。因此,這個整個對象圖將一直存在,直到視圖控制器的視圖被解除分配。

當您離開視圖控制器時,UIKit卸載視圖以釋放內存。當視圖被解除分配時,你的maskAnim也是如此。當您回到視圖控制器時,UIKit會根據您使用的技術重建您的視圖層次結構,方法是重新從其.xib文件重新加載,或者調用loadView。

因此,您需要確保在UIKit重建視圖層次結構後,您用來設置maskAnim的代碼被再次調用。有四種方法可以考慮:loadView,viewDidLoad,viewWillAppear:和viewDidAppear :.

如果您使用該方法構建視圖層次結構(而不​​是從.xib加載它),loadView是一個合理的選項,但是您必須更改代碼以使其不依賴於自身.view屬性,它會遞歸地觸發loadView。 viewDidLoad也是一個不錯的選擇。對於這兩個選項中的任何一個,您都需要小心,因爲UIKit可能會在viewDidLoad之後調整視圖的大小,如果它沒有以合適的大小構建的話。這可能會導致錯誤,因爲你的代碼依賴於self.view.frame.size.width。

如果您在viewWillAppear:或viewDidAppear:中設置了動畫,則可以確定您的視圖的框架將是適當的維度,但您需要注意這些方法,因爲它們可以在視圖被加載,並且你不想多次添加你的whiteview子視圖。

什麼我可能做的是使whiteView一個保留的財產,並延遲加載它在viewWillAppear中:是這樣的:

- (UIView *)setupWhiteViewAnimation { 
    // Execute your code above to setup the whiteView without adding it 
    return whiteView; 
} 

- (void)viewWillAppear:(BOOL)animated { 
    [super viewWillAppear:animated]; 
    if (!self.whiteView) { 
     self.whiteView = [self setupWhiteViewAnimation]; 
     [self.view addSubview:self.whiteView]; 
    } 
} 

- (void)viewDidUnload { 
    self.whiteView = nil; // Releases your whiteView when the view is unloaded 
    [super viewDidUnload]; 
} 

- (void)dealloc { 
    self.whiteView = nil; // Releases your whiteView when the controller is dealloc'd 
    [super dealloc]; 
}