Pages

June 19, 2013

Flip UIButton title and image

Let's say we have a UIButton which can assume two state. With this convenient function we can do a flip animation between two images and two titles.


/** Flip animation for title and image of a button.

 The button action does not change. This function changes only the title and the image associated to the button.

 @param baseBtn Shared button.
 @param baseView A container View. It only serves for animation effect.
 @param title1 String of the first title.
 @param img1 First image.
 @param title2 String of the second title.
 @param img2 Second image.
 @return Returns true on success, false otherwise.

 */
+ (BOOL)flipButton:(UIButton *)baseBtn ofView:(UIView *)baseView
        withTitle1:(NSString *)title1 img1:(UIImage *)img1
        withTitle2:(NSString *)title2 img2:(UIImage *)img2 {

    NSString *newTitle;
    UIImage *newImage;
    UIViewAnimationTransition flip;

    if ([baseBtn.currentTitle isEqualToString:title1]) {
        newTitle = title2;
        newImage = img2;
        flip = UIViewAnimationTransitionFlipFromRight;
    } else if ([baseBtn.currentTitle isEqualToString:title2]) {
        newTitle = title1;
        newImage = img1;
        flip = UIViewAnimationTransitionFlipFromLeft;
    } else {
        LogError(@"No button found with title: '%@' or '%@'", title1, title2);
        return NO;
    }

    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration: 0.50f];
    [UIView setAnimationTransition:flip forView:baseView cache:YES];

    [baseBtn setTitle:newTitle forState:UIControlStateNormal];
    [baseBtn setImage:newImage forState:UIControlStateNormal];

    [UIView commitAnimations];

    return YES;
}



Download the ready-for-use source file (.m) of Flip UIButton title and image

No comments:

Post a Comment