簡體   English   中英

iPhone-如何在按下按鈕時為按鈕設置動畫?

[英]iPhone - How to animate a button when pressed?

單擊iPhone按鈕時,是否可以制作自定義動畫? 我想要類似App Store的按鈕-它顯示價格,然后單擊它,它會更改顏色,文本更改為立即購買,然后再次單擊它,便完成了購買。

UIViewAnimationTransition僅包含一些不能提供全部功能的值。 是否可以使用動畫來做類似的事情:

- (IBAction) changeButtonDisplay:(id)sender {

  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationDuration:0.8];
  [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:purchaseButton cache:NO]; //the built in UIViewAnimationTransition values don't provide enough flexibility

  [purchaseButton setTitle:@"Buy Now" forState:UIControlStateNormal];
  [purchaseButton setBackgroundColor:[UIColor greenColor]];
  [purchaseButton addTarget:self action:@selector(purchaseItems:) forControlEvents:UIControlEventTouchUpInside];

  [UIView commitAnimations];

}

該代碼可以正常工作,並且將顯示正確的過渡效果,並允許第二次單擊以執行正確的操作,但是標題和顏色會立即更改,而不是采用平滑的動畫。 是否可以輕松制作這樣的動畫,我是否必須創建UIButton子類並“手動”制作動畫? 如果是這樣,我將不得不覆蓋哪種方法?

有兩個單獨的按鈕可以執行每個操作並看上去各不相同,而不僅僅是更改按鈕的標題和目標等。 然后,當您按下按鈕時,調用一個方法,該方法將從其超級視圖中刪除當前按鈕,並將新按鈕添加到該視圖的位置。 將其包裝在一些UIView動畫塊中,您應該獲得動畫。

另外,為使此方法起作用,您需要在按鈕的超級視圖上設置動畫過渡。 因此,擁有“容器視圖”可能很方便,然后將您的按鈕添加為該視圖的子視圖。

偽代碼可能看起來像這樣:

[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.8];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:buttonConteinerView cache:NO]; //the built in UIViewAnimationTransition values don't provide enough flexibility

[purchaseButton retain];
[purchaseButton removeFromSuperView];

[buttonContainerView addSubview:secondPurchaseButton];

[UIView commitAnimations];

標准的UIView可以滿足您的需求。 UIView的backgroundColor是可設置動畫的屬性。

我將通過子類化UIView來制作自己的“按鈕”,或者子類化UIButton並為其添加子視圖。 (注意:UIButton在2.2中對此感到痛苦,在3.0中不確定)

每個文本狀態都需要一個UILabel:

UILabel *textForStateOne;
UILabel *textForStateTwo;

您可以更改父視圖的背景顏色。

因此,您可以在新的按鈕類中創建一個方法:

 -(void)toggleState{

myState = !myState;

  if(myState){

      [UIView beginAnimations:nil context:NULL];
      [UIView setAnimationDuration:0.8];

      [textForStateOne setAlpha:1.0]
      [textForStateTwo setAlpha:0.0]

      [self setBackgroundColor:[UIColor greenColor]];

      [UIView commitAnimations];


  } else{

       //do the opposite here

  }




}
UIView *btnView4=button;
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
[UIView setAnimationTransition:UIViewAnimationTransitionCurlUp forView:btnView4 cache:YES];
[UIView commitAnimations];``

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM