如何动画一个UIView离开屏幕到右边,然后从左边重新出现



我有一个视图,它包含在我的应用程序的主视图中(屏幕中间的一个正方形)。我编写了以下代码,如果向左滑动视图,它将从屏幕向右滑动:

- (IBAction)swipeLeft:(id)sender
{
    CGRect initCardViewFrame = self.cardView.frame;
    CGRect movedCardToRightViewFrame = CGRectMake(initCardViewFrame.origin.x + 1000, initCardViewFrame.origin.y, initCardViewFrame.size.width, initCardViewFrame.size.height);
    [UIView animateWithDuration:0.7
                     animations:^{self.cardView.frame = movedCardToRightViewFrame;}
                     completion:nil];
}

这工作得很好,但是我想扩展代码,这样一旦正方形离开屏幕的右侧,它就会从左侧回到中间。我真的不知道如何在窗口的左边"重新绘制"它,然后在中间滑动它。我试过重做帧,但动画只显示动画块中的最后一帧运动。我假设我需要将视图推出屏幕,然后在屏幕左侧的外部重新绘制它,然后将其滑动到中间。当然,除非有更直观的方法。

更新:

我已经在下面回答了这个问题,但我忍不住认为有一个更好的方法来做到这一点,而不需要在彼此内部嵌套UIView动画。这是解决这个问题的唯一办法吗?

最后在"completion"参数中添加了以下代码:

completion:^(BOOL finished)
{ 
    self.cardView.frame = moveCardToLeftViewFrame; 
    [UIView animateWithDuration:0.4 
                     animations:^{self.cardView.frame = initCardViewFrame;}
                     completion:nil];
}];

注* moveCardToLeftViewFrame是一个CGRect,它将视图放置在可见窗口的左侧。因此,当它向右滑动后,它被放置在屏幕左侧的外部,然后再滑回中间。

您可以在以下情况下使用此代码:

  1. 视图将从屏幕左侧退出,并从右侧进入。
  2. 视图将从屏幕右侧退出,并从左侧进入。

代码中伤说:

- (void)animateViewWithTransformation:(MyEnumAnimationTransformation)animationTransformation withDuration:(CGFloat)duration {
    CGFloat goOutOffScreenToX, cameInToScreenFromX;
    switch (animationTransformation) {
        case goOutToLeftGetInFromRight:
            goOutOffScreenToX = -1 * [UIScreen mainScreen].applicationFrame.size.width;
            cameInToScreenFromX = [UIScreen mainScreen].applicationFrame.size.width;
            break;
        case goOutToRightGetInFromLeft:
            goOutOffScreenToX = [UIScreen mainScreen].applicationFrame.size.width;
            cameInToScreenFromX = -1 * [UIScreen mainScreen].applicationFrame.size.width;
            break;
        default:
            break;
    }
    CGRect originViewFrame = self.frame;
    [UIView animateWithDuration:duration
                     animations:^{[self setX:goOutOffScreenToX];}
                     completion:^(BOOL finished)
                                { 
                                    [self setX:cameInToScreenFromX];
                                    [UIView animateWithDuration:duration
                                                     animations:^{[self setX:originViewFrame.origin.x];}
                                                     completion:nil];
                                }];
}

相关内容

最新更新