button press animation

Lukas picture Lukas · Oct 17, 2012 · Viewed 11.2k times · Source

So I've searched a lot but I didn't find an answer for my problem.

I want to make a button that would have two images, first image that is when button is in normal state, the other one when it is in highlighting state. The problem is that i want these images to change in animated manner, for example the first image fades out, when the second fades in. And they change in such a way that the animation time remains constant.

The only way I thought is, to make a custom button, add couple of ImageViews and on button touch down event, one ImageView fades in, other fades out, on button touch up event, I could do the opposite. But this method doesn't seem the most suitable. Is there a better option that I am not seeing?

Answer

Vinod ram picture Vinod ram · Oct 17, 2012
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    myButton.frame = CGRectMake(80, 50, 150, 40);
    [myButton setTitle:@"Say, Hi!" forState:UIControlStateNormal];
    [myButton setBackgroundImage:[UIImage imageNamed:@"xyz.png"] forState:UIControlStateNormal];
    [myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:myButton];


-(IBAction)buttonClicked:(UIButton *)sender
{
    [UIView animateWithDuration:0.7f
                     animations:^
     {
         [sender setAlpha:0.5f];
     }
                     completion:^(BOOL finished)
     {
         [sender setAlpha:1.0f];
        [sender setBackgroundImage:[UIImage imageNamed:@"abc.png"] forState:UIControlStateNormal];   }
     ];
}

you can set the animation duration and also alpha accordingly.