在UIButton中实现动画

dom*_*lao 7 iphone

我是可可和iphone编程的新手,我想在UIButton中实现动画.例如,我创建了一个带有方形图像的自定义UIButton.然后当我按下那个UIButton时,方形图像会翻转.请注意,方形图像是UIButton的图像.

[UIButton setImage:[UIImage imageNamed:@"square.png"]];
Run Code Online (Sandbox Code Playgroud)

ank*_*nka 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];
}
Run Code Online (Sandbox Code Playgroud)

奇迹般有效.

干杯,安卡


小智 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];
Run Code Online (Sandbox Code Playgroud)

}

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

}
Run Code Online (Sandbox Code Playgroud)