1

I wanted to know if is possible to have a UIButton which when untouched animates?

Not sure if that makes perfect sense. I have a UIButton which I have placed via IB on my XIB. I am using a type Custom with my own 75x75 image for control state default. When the user touches the button i have no custom image set so it just darkens which is fine.

However, when the button is not touched, I would like it to animate between two or three different custom images to give it an effect of 'glowing' around the outer edges. Is this possible to do?

Paul Morris
  • 1,763
  • 10
  • 33
  • 47

2 Answers2

4

You'll probably need to go down to the Core Animation layer. The shadow property of the UIButton's layer is animatable, so you can create a repeating CABasicAnimation I change the shadow color/size and add it to the layer. The following code worked for me.

button.layer.shadowPath = [[UIBezierPath bezierPathWithRect:CGRectInset(button.bounds, -3, -3)] CGPath];
button.layer.shadowColor = [[UIColor whiteColor] CGColor];
button.layer.shadowOpacity = 1.0f;

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"shadowColor"];
animation.fromValue = (id)[[UIColor darkGrayColor] CGColor];
animation.toValue = (id)[[UIColor lightGrayColor] CGColor];
animation.duration = 1.0f;
animation.autoreverses = YES;
animation.repeatCount = NSIntegerMax;

[button.layer addAnimation:animation forKey:@"shadow"];

And attach these methods appropriate to the button's control events.

-(IBAction)userDidTouchDown:(UIButton *)sender
{
    [button.layer removeAnimationForKey:@"shadow"];
}

-(IBAction)userDidTouchUp:(UIButton *)sender
{

    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"shadowColor"];
    animation.fromValue = (id)[[UIColor darkGrayColor] CGColor];
    animation.toValue = (id)[[UIColor lightGrayColor] CGColor];
    animation.duration = 1.0f;
    animation.autoreverses = YES;
    animation.repeatCount = NSIntegerMax;

    [button.layer addAnimation:animation forKey:@"shadow"];
}

You can play around with the shadow values (particularly the path) to get it right for you. Don't forget to attach userDidTouchUp: with both the touch up inside and touch up outside events.

Ash Furrow
  • 12,391
  • 3
  • 57
  • 92
-1

You will need to have a custom view, as UIButton cannot do animation. UIView for the whole frame with two subviews: Button on the bottom, uiimageview on top.

You set the animationImages property of the uiimageview to your frames. Hide/show the uiimageview as needed.

Mitchell Currie
  • 2,769
  • 3
  • 20
  • 26