0

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

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 慢,所以当我关闭视图时,按钮会在后面停留一秒钟......我必须做些什么才能获得相同的速度?

4

1 回答 1

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);
    }];
}
于 2012-06-09T07:16:27.707 回答