2

我在使用 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;
}

}

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

最好的祝福

自由宁静

4

1 回答 1

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;
    }
}
于 2013-01-09T13:17:23.400 回答