2012-05-29 260 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