Skip to content

Instantly share code, notes, and snippets.

@qnoid
Created August 2, 2013 14:29
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save qnoid/6140282 to your computer and use it in GitHub Desktop.
Save qnoid/6140282 to your computer and use it in GitHub Desktop.
Animate an UIBarButtonItem that has been assigned a UIButton as its customview. The UIButton uses an image that is mirrored on the X axis hence appear as if it's rotating.
-(IBAction)tap:(id)sender
{
UIBarButtonItem *refresh = self.navigationItem.rightBarButtonItem;
CALayer *layer = ((UIButton*)refresh.customView).imageView.layer;
CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
rotate.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear];
rotate.fromValue = @(0);
rotate.toValue = @(2 * M_PI);
rotate.duration = 1.0;
rotate.repeatCount = HUGE_VALF;
[layer addAnimation:rotate forKey:@"transform.rotation.z"];
[self performSelector:@selector(done) withObject:nil afterDelay:5.0];
}
-(void)done
{
UIBarButtonItem *refresh = self.navigationItem.rightBarButtonItem;
CALayer *layer = ((UIButton*)refresh.customView).imageView.layer;
[layer removeAnimationForKey:@"transform.rotation.z"];
}
@bragisig
Copy link

bragisig commented Dec 1, 2013

Thanks for sharing, just what I was looking for.

@tinybot-ca
Copy link

This seems straightforward but I can't seem to get this to work - does anyone have any sample code or a sample project I could look at? Here's what I've put in viewDidLoad:

UIButton *refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
UIImage *refreshButtonImage = [UIImage imageNamed:@"BarButtonIconHelp"];
[refreshButton setFrame:CGRectMake(0, 0, 20, 20)];
[refreshButton setBackgroundImage:refreshButtonImage forState:UIControlStateNormal];
[refreshButton addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *refreshBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:refreshButton];
self.navigationItem.rightBarButtonItem = refreshBarButtonItem;

I can confirm that the tap method is being called, but no animation is occurring! (Sorry if this is obvious, I'm a beginner.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment