2009-11-05 120 views
7

我是新來的可可和iphone編程,我想在UIButton中實現動畫。例如,我創建了一個帶有方形圖像的自定義UIButton。然後當我按下那個UIButton時,方形圖像會翻轉。請注意,正方形圖像是UIButton的圖像。在UIButton中實現動畫

[UIButton setImage:[UIImage imageNamed:@"square.png"]]; 

回答

6

下面是按下按鈕(帶背景圖像)時按下的完整代碼。 基本上你需要兩個按鈕和一個容器視圖。

///// .H file code.... 


    //Container views used for flipping the bars to show whose turn it is 

    UIButton* btn1; 
    UIButton* btn2; 
UIView *BarContainerView; 

///// .M file code.... 

- (void)viewWillAppear:(BOOL)animated 
{ 

    BarContainerView = [[UIView alloc] initWithFrame:CGRectMake(20, 30, 103, 150)]; 

btn1 = [[UIButton buttonWithType:UIButtonTypeRoundedRect]retain]; 
[btn1 addTarget:self action:@selector(btn1_click) forControlEvents:UIControlEventTouchUpInside]; 
[btn1 setBackgroundImage:[UIImage imageNamed:@"image1.png"] forState:UIControlStateNormal]; 
btn1.frame = CGRectMake(0, 0, 103, 150); 

btn2 = [[UIButton buttonWithType:UIButtonTypeRoundedRect]retain]; 
[btn2 addTarget:self action:@selector(btn2_click) forControlEvents:UIControlEventTouchUpInside]; 
[btn2 setBackgroundImage:[UIImage imageNamed:@"image2.png"] forState:UIControlStateNormal]; 
btn2.frame = CGRectMake(0, 0, 103, 150); 

[BarContainerView addSubview:btn1]; 
[self.view addSubview:BarContainerView]; 
[self.view bringSubviewToFront:BarContainerView]; 

}

- (void) btn1_click 
{ 

[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:0.75]; 
[UIView setAnimationDelegate:self]; 

[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:BarContainerView cache:YES]; 

[btn1 removeFromSuperview]; 
[BarContainerView addSubview:btn2]; 
[UIView commitAnimations]; 

} 

- (void) btn2_click 
{ 

[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration:0.75]; 
[UIView setAnimationDelegate:self]; 

[UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:BarContainerView cache:YES]; 

[btn2 removeFromSuperview]; 
[BarContainerView addSubview:btn1]; 
[UIView commitAnimations]; 

} 
9

我有同樣的問題,我解決它在一個非常類似的方式。我只是將UIButton分類並實現了這樣一種方法:

- (void) flipBackgroundImage:(UIImage*) image 
{ 
    [UIView beginAnimations:@"flipbutton" context:NULL]; 
    [UIView setAnimationDuration:0.4]; 
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromRight forView:self cache:YES]; 

    [self setBackgroundImage:image forState:UIControlStateNormal]; 

    [UIView commitAnimations]; 
} 

工程就像一個魅力。

乾杯, 又名