iPhone/iPad - 核心动画 - CGAffineTransformMakeTranslation不会修改框架

4
我面临一个非常烦人的问题。 下面是上下文:我有一个“矩形”视图,它是主视图的子视图。 我想做的很简单,当我点击一个按钮时,我希望“矩形”视图在x轴方向上移动,以便消失。然后我添加一个新的子视图,并将其平移以取代先前的“矩形”视图。 这很好用,除了如果我再次按下该按钮,动画将从屏幕外开始,就像CGAffineTransformMakeTranslation没有改变我的新“矩形”视图的框架一样。 以下是代码:
UIView *rectangleView = [detailView viewWithTag:4]; //the actual frame is (20.0, 30.0, 884.0, 600.0)

[UIView animateWithDuration:0.5 animations:^{
    [rectangleView setTransform:CGAffineTransformMakeTranslation(-1000, 0)];
} completion:^(BOOL finished) {
    [rectangleView removeFromSuperview];
    UIView *otherView = [[UIView alloc] initWithFrame:CGRectMake(1020.0, 30.0, 884.0, 600.0)];
    [otherView setBackgroundColor:[UIColor purpleColor]];
    [otherView setTag:4];
    [detailView addSubview:otherView];
    [UIView animateWithDuration:0.5 animations:^{
        [otherView setTransform:CGAffineTransformMakeTranslation(-1000, 0)];
    } completion:^(BOOL finished) {
        [otherView release];
    }];
}];
2个回答

3
在添加第二个视图后,您已经将其变换设置为等于CGAffineTransformMakeTranslation(-1000,0),当您想要删除该视图时,您设置完全相同的变换-因此它将没有任何效果。 在这里,您有两个选项:
  1. 应用变换到视图已有的变换中:

    CGAffineTransform newTransform = CGAffineTransformConcat(rectangleView.transform, CGAffineTransformMakeTranslation(-1000, 0));
    [rectangleView setTransform:newTransform];
    
  2. 不要使用变换,直接操作视图位置(例如通过其中心属性)

    UIView *rectangleView = [detailView viewWithTag:4]; //实际框架是 (20.0, 30.0, 884.0, 600.0)
    CGAffineTransform tf = CGAffineTransformMakeTranslation(-1000, 0);
    [UIView animateWithDuration:0.5 animations:^{
        [rectangleView setCenter: CGPointApplyAffineTransform(rectangleView.center, tf)];
    } completion:^(BOOL finished) {
        [rectangleView removeFromSuperview];
        UIView *otherView = [[UIView alloc] initWithFrame:CGRectMake(1020.0, 30.0, 884.0, 600.0)];
        [otherView setBackgroundColor:[UIColor purpleColor]];
        [otherView setTag:4];
        [detailView addSubview:otherView];
        [UIView animateWithDuration:0.5 animations:^{
            [otherView setCenter: CGPointApplyAffineTransform(otherView.center, tf)];
        } completion:^(BOOL finished) {
            [otherView release];
        }];
    }];
    

能运行了,非常感谢 Vladimir。我还有一个(可能很傻的)问题。有没有办法测试一个视图是否具有变换?就像 if(![rectangleView transform]) NSLog(@"没有变换,所以我不需要拼接") 这样的? - Dabrut
@Dave,你可以使用CGAffineTransformIsIdentity函数检查视图的变换。 - Vladimir

1
尝试使用center属性进行动画处理,而不是使用仿射变换。变换不是可加的,因此您的第二个动画(当您新添加的详细视图被移出屏幕时)实际上并没有改变视图,因为它已经应用了该平移(-1000,0)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接