Search code examples
iphoneobjective-ccocoa-touchuikitcore-animation

Is it possible to animate the width of a UIButton of UIButtonStyleCustom type?


I have an animation on frame size which works fine when the UIButton is a UIButtonTypeRoundedRect. But has no visible affect when I am using a UIButtonStyleCustom with background image. My animation code is here:

[UIView beginAnimations:@"MyAnimation" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
[UIView setAnimationDuration:0.25];
CGRect tempFrame = myButton.frame;
tempFrame.size.width = tempFrame.size.width + 100.0f;
myButton.frame = tempFrame;
[UIView commitAnimations];

Thanks for the help!


Solution

  • Hey guys, I finally resolve my problem. I subclassed UIView and added two UIImageViews and an UIButton to it. The animation is perfectly good now!

    Here is the code:

    .h

    #import <UIKit/UIKit.h>
    
    @interface NNAnimatableButton : UIView {
    
        UIImageView *backgroundImageView;
        UIImageView *imageView;
        UIButton *button;
    }
    
    @property (nonatomic, retain) UIImageView *backgroundImageView;
    @property (nonatomic, retain) UIImageView *imageView;
    @property (nonatomic, retain) UIButton *button;
    
    @end
    

    .m

    #import "NNAnimatableButton.h"
    
    @implementation NNAnimatableButton
    
    @synthesize backgroundImageView, imageView, button;
    
    - (id)initWithFrame:(CGRect)frame {
        if ((self = [super initWithFrame:frame])) {
    
            CGRect rect = CGRectMake(0.0f, 0.0f, frame.size.width, frame.size.height);
    
            NSUInteger autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleBottomMargin;
    
            // Initialization code.
            backgroundImageView = [[UIImageView alloc] initWithFrame:rect];
            backgroundImageView.autoresizingMask = autoresizingMask;
    
            imageView = [[UIImageView alloc] initWithFrame:rect];
            imageView.autoresizingMask = autoresizingMask;
            imageView.contentMode = UIViewContentModeCenter;
    
            button = [UIButton buttonWithType:UIButtonTypeCustom];
            button.autoresizingMask = autoresizingMask;
            [button setFrame:rect];
    
            [self addSubview:backgroundImageView];
            [self addSubview:imageView];
            [self addSubview:button];
    
            [backgroundImageView release];
            [imageView release];
        }
        return self;
    }
    
    - (void)dealloc {
    
        [backgroundImageView release];
        [imageView release];
        [button release];
    
        [super dealloc];
    }
    
    @end