2012-05-29 262 views
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?

回答

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,它可以是任何数据类型(只要它是一个对象而不是一个原语)。它基本上是动画发生时传递给委托的数据。

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]; 
+0

我编译了该代码,并且还添加了“self.myButton.frame = [UIColor redColor];”只是这样我才能看到模拟器中没有发生任何结果。你知道哪里出了问题吗?而且,为什么“开始动画:上下文:”气馁?谢谢 – pasawaya

+0

要设置颜色,你不想使用框架,请使用self.myButton.backgroundColor = [UIColor redColor];但是,我不认为设置颜色是可以动画的。至于为什么它不受欢迎,我不知道 - 这就是苹果在文档中所说的。 – rdelmar

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)]; 

对于上下文看documentation