beginAnimations:子视图的动画比视图的动画慢

时间:2012-06-08 17:35:54

标签: iphone xcode animation uiview subview

我有一点问题,我尝试以这种方式显示带有动画的视图:

self.vistaAiuti = [[UIView alloc] initWithFrame:CGRectMake(10, -200, 300, 200)];
self.vistaAiuti.backgroundColor = [UIColor blueColor];


UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
closeButton.frame = CGRectMake(50, 140, 220, 40);
[closeButton setTitle:@"Go back" forState:UIControlStateNormal];
[closeButton addTarget:self action:@selector(closeView:) forControlEvents:UIControlEventTouchUpInside];

[self.vistaAiuti addSubview:closeButton];    
[self.view addSubview:self.vistaAiuti];

[UIView beginAnimations:@"MoveView" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:0.5f];
self.vistaAiuti.frame = CGRectMake(10, 0, 300, 200);
[UIView commitAnimations];  

这是关闭它:

[UIView beginAnimations:@"MoveView" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
[UIView setAnimationDuration:0.5f];
self.vistaAiuti.frame = CGRectMake(10, -200, 300, 0);
[UIView commitAnimations]; 

问题是vista aiuto上的按钮比vistaAiuti慢,所以当我关闭视图时,按钮会留下一段时间......我要做的事情有同样的速度吗?

1 个答案:

答案 0 :(得分:3)

问题是在关闭动画中vistaAiuti框架被设置为零高度。按钮似乎滞后,但真正发生的是下面的父视图缩小到零高度和-200 origin.y。

将关闭动画目标框架更改为:

self.vistaAiuti.frame = CGRectMake(10, -200, 300, 200);

另外,还有一些建议:

将视图的创建与显示分开。这样,每次要显示时都不会添加其他子视图。

- (void)addVistaAiutiView {

    // your creation code
    self.vistaAiuti = [[UIView alloc] initWithFrame:CGRectMake(10, -200, 300, 200)];
    self.vistaAiuti.backgroundColor = [UIColor blueColor];

    UIButton *closeButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    closeButton.frame = CGRectMake(50, 140, 220, 40);
    [closeButton setTitle:@"Go back" forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(closeView:) forControlEvents:UIControlEventTouchUpInside];

    [self.vistaAiuti addSubview:closeButton];    
    [self.view addSubview:self.vistaAiuti];
}

使用块动画,它更易于编写和易于阅读

- (BOOL)vistaAiutiIsHidden {

    return self.vistaAiuti.frame.origin.y < 0.0; 
}

- (void)setVistaAiutiHidden:(BOOL)hidden animated:(BOOL)animated {

    if (hidden == [self vistaAiutiIsHidden]) return;  // do nothing if it's already in the state we want it

    CGFloat yOffset = (hidden)? -200 : 200;           // move down to show, up to hide
    NSTimeInterval duration = (animated)? 0.5 : 0.0;  // quick duration or instantaneous

    [UIView animateWithDuration:duration animations: ^{
        self.vistaAiuti.frame = CGRectOffset(0.0, yOffset);
    }];
}