UIView动画无法正常工作

时间:2013-01-09 13:07:22

标签: ios animation subview

我在UIView子视图动画方面遇到了一些问题。我要做的是,当您按下主视图时,子视图将从顶部向下滑动,在下一个点击时,它将向上滑动并被移除。但是在当前状态下,它只执行第一次点击命令,在第二次点击时,它会显示一个nslog,但删除视图和动画不起作用。

以下是事件处理函数中的代码:

- (void)tapGestureHandler: (UITapGestureRecognizer *)recognizer
{
NSLog(@"tap");

CGRect frame = CGRectMake(0.0f, -41.0f, self.view.frame.size.width, 41.0f);
UIView *topBar = [[UIView alloc] initWithFrame:frame];
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"topbar.png"]];
topBar.backgroundColor = background;

if (topBarState == 0) {
     [self.view addSubview:topBar];
    [UIView animateWithDuration:0.5 animations:^{topBar.frame = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 41.0f);}];
    topBarState = 1;
} else if (topBarState == 1){
    [UIView animateWithDuration:0.5 animations:^{topBar.frame = CGRectMake(0.0f, -41.0f, self.view.frame.size.width, 41.0f);} completion:^(BOOL finished){[topBar removeFromSuperview];}];

    NSLog(@"removed");
    topBarState = 0;
}

}

如何制作以使子视图动画并正确删除?

最好的问候

FreeSirenety

1 个答案:

答案 0 :(得分:2)

你总是设置topBar框架,y = -41,所以对于topBarState = 1,动画适用于y=-41 to y=-41并且似​​乎无法正常工作

CGRect frame = CGRectMake(0.0f, -41.0f, self.view.frame.size.width, 41.0f);
UIView *topBar = [[UIView alloc] initWithFrame:frame];

每次创建视图topBar。
在.h中声明topBar并在viewDidLoad中声明init。

- (void)viewDidLoad {
    CGRect frame = CGRectMake(0.0f, -41.0f, self.view.frame.size.width, 41.0f);
    topBar = [[UIView alloc] initWithFrame:frame];
    UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"topbar.png"]];
    topBar.backgroundColor = background;
        [self.view addSubview:topBar];
    topBarState = 0;
}

- (void)tapGestureHandler: (UITapGestureRecognizer *)recognizer
{
    if (topBarState == 0) {
            [UIView animateWithDuration:0.5 animations:^{topBar.frame = CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 41.0f);}];
            topBarState = 1;
    } else if (topBarState == 1){
        [UIView animateWithDuration:0.5 animations:^{topBar.frame = CGRectMake(0.0f, -41.0f, self.view.frame.size.width, 41.0f);} completion:^(BOOL finished){[topBar removeFromSuperview];}];
        topBarState = 0;
    }
}