Created
August 2, 2013 14:29
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-(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"]; | |
} | |
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
Thanks for sharing, just what I was looking for.