3

在我正在制作的应用程序中,我试图让一个按钮在屏幕外启动并在屏幕上移动。我不确定如何从屏幕外的按钮开始,但我知道一旦我弄清楚了,我可以执行以下代码:

[UIView beginAnimation:@"animate" context: nil];
[UIView setAnimationDuration:3];
self.myButton.frame = CGRectMake (20, 100, 40, 80);
//Other animations
[UIView commitAnimations];

此外,在该行[UIView beginAnimation:@"animate" context:nil];中,上下文参数是否要求 CGContextRef?

4

3 回答 3

5

我假设您正在询问如何让按钮从屏幕外动画到屏幕上,为此只需将按钮原点位置设置为位于屏幕外的坐标。

self.myButton.frame = CGRectMake(-80, 100, 40, 80);

完成此操作后,您可以使用发布的代码在屏幕上制作动画。请记住,按钮将从第一个位置移动到第二个位置,这意味着如果您使用我使用的坐标,按钮将从左侧移动到屏幕上,而 y 位置不会改变。请记住,在 setAnimationDuration 中分配的时间内,您将按钮放置得越远,它必须移动到屏幕上的速度就越快。

所以从左边动画到屏幕上

self.myButton.frame = CGRectMake(-80, 100, 40, 80);
// begin animation block    
[UIView beginAnimations:@"animate" context: nil];
[UIView setAnimationDuration:3];
self.myButton.frame = CGRectMake (20, 100, 40, 80);
// commit frame changes to be animated
[UIView commitAnimations];

此外,如果该按钮以前在屏幕上,它似乎会从屏幕上传送,然后在使用该代码时滑回。

哦,要回答您关于上下文的问题,不,它不必是 CGContextRef,它可以是任何数据类型(只要它是对象而不是原始数据)。它基本上是动画发生时传递给委托的数据。

于 2012-05-29T00:49:22.537 回答
3

BeginAnimation:context: 在 iOS 4.0 或更高版本中不鼓励使用,您应该使用基于块的方法之一。您应该设置原始帧,使其不在屏幕上。这是一个稍微延迟后将按钮从右侧移入的示例:

self.myButton.frame = CGRectMake (340, 250, 40, 80);
    [self.view addSubview:myButton];
    [UIView animateWithDuration:5 delay:.2 options: UIViewAnimationOptionLayoutSubviews animations:^{
    self.myButton.frame = CGRectMake (140, 250, 40, 80);
    //Other animations
    }
     completion:nil];
于 2012-05-29T00:56:19.180 回答
2

如果您不使用 xibs,您可以在屏幕外设置按钮的框架viewDidLoad(如果您使用的是 xibs,请将其滑出视图):

 //create the button or get it from the xib
 CGRect rect = self.myButton.frame;
 rect.origin.x=-200;//or a good point to hide the button
 self.myButton.frame=rect;

然后当你想为按钮设置动画时,你可以使用块动画:

 [UIView animateWithDuration:0.3f delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        self.myButton.frame=SET_YOUR_FRAME;
    } completion:^(BOOL finished)];

有关上下文,请参阅文档

于 2012-05-29T00:58:51.877 回答