2009-11-05 5 views
7

私はココアとiPhoneプログラミングを初めて使い、UIButtonでアニメーションを実装したいと思います。たとえば、正方形のイメージを持つカスタムUIButtonを作成します。そのUIButtonを押すと正方形の画像が反転します。正方形の画像は、UIButtonの画像です。UIButtonでアニメーションを実装する

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

答えて

6

以下は、ボタンを押したときに(背景画像付き)ボタンを反転させるための完全なコードです。 基本的に2つのボタンとコンテナビューが必要です。

///// .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をサブクラス化し、そのようなメソッドを実装しました:

魅力のように動作します。

乾杯、 anka

関連する問題