我有一个奇怪的bug,我似乎找不到。我正在创建一个闪亮的小动画,效果很好,但由于某种原因,当我通过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;发布于 2011-07-07 12:32:45
您的maskAnim由maskLayer保留,由白视图层保留,由whiteView保留,由self.view保留。因此,整个对象图将一直存在,直到您的视图控制器的视图被取消分配。
当您离开视图控制器时,UIKit会卸载您的视图以释放内存。当视图被取消分配时,您的maskAnim也会被取消分配。当您导航回视图控制器时,UIKit会根据您使用的技术,通过从其.xib重新加载视图层次结构,或者通过调用loadView重新构建视图层次结构。
因此,您需要确保在UIKit重新构建视图层次结构后再次调用用于设置maskAnim的代码。您可以考虑四种方法: loadView、viewDidLoad、viewWillAppear:和viewDidAppear:。
如果您使用该方法构建视图层次结构(而不是从.xib加载视图层次结构),则loadView是一个明智的选择,但您必须更改代码,使其不依赖于self.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];
}https://stackoverflow.com/questions/6605111
复制相似问题