Flipping bar button like iTunes

This is the example for how to create flipping bar button like iTunes. I faced the same problem while developing solutions for first time, after looking at iTunes app more closely..it seems the flipping thing in Navigation Bar is not a BarButton but button with images ( It does not show highlighted effect ).

image

All we need to do is use custom UIBarButtonItem with CustomView for this.

Step 1: Create UIBarButton with CustomView

barButtonSuperView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 34, 30)];
barButtonPrimaryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 34, 30)];
UIButton * primaryButton = [UIButton buttonWithType:UIButtonTypeCustom];
primaryButton.frame = CGRectMake(0, 0, 34, 30);
[primaryButton setBackgroundColor:[UIColor greenColor]];
[primaryButton addTarget:self action:@selector(flipAction:) forControlEvents:UIControlEventTouchUpInside];
[barButtonPrimaryView addSubview:primaryButton];
 
barButtonSecondaryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 34, 30)];
UIButton * secondaryButton = [UIButton buttonWithType:UIButtonTypeCustom];
secondaryButton.frame = CGRectMake(0, 0, 34, 30);
[secondaryButton setBackgroundColor:[UIColor redColor]];
[secondaryButton addTarget:self action:@selector(flipAction:) forControlEvents:UIControlEventTouchUpInside];
[barButtonSecondaryView addSubview:secondaryButton];
 
// self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:barButtonSuperView] autorelease];
UIView * barButtonSuperSuperView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 34, 30)];
barButtonSuperSuperView.backgroundColor = [UIColor viewFlipsideBackgroundColor];
[barButtonSuperSuperView addSubview:barButtonSuperView];
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:barButtonSuperSuperView] autorelease];
[barButtonSuperSuperView release], barButtonSuperSuperView = nil;

Step 2: Use UIView transition effects

[UIView beginAnimations:@"BarButtonViewAnimation" context:NULL];
[UIView setAnimationDuration:kTransitionDuration];
[UIView setAnimationTransition:([barButtonPrimaryView superview] ?
    UIViewAnimationTransitionFlipFromLeft : UIViewAnimationTransitionFlipFromRight)
    forView:barButtonSuperView cache:YES];
 
if ([barButtonPrimaryView superview]) {
    [barButtonPrimaryView removeFromSuperview];
    [barButtonSuperView addSubview:barButtonSecondaryView];
} else {
    [barButtonPrimaryView removeFromSuperview];
    [barButtonSuperView addSubview:barButtonPrimaryView];

[UIView commitAnimations];

Here is the complete demo code.