Skip to content

Instantly share code, notes, and snippets.

@klaw23
Created July 31, 2012 02:01
Show Gist options
  • Select an option

  • Save klaw23/3212699 to your computer and use it in GitHub Desktop.

Select an option

Save klaw23/3212699 to your computer and use it in GitHub Desktop.
A subclass of UIButton that automatically stretches the background images for all button states.
#import <UIKit/UIKit.h>
@interface AutoStretchButton : UIButton
// Call this if you modify the background images after initialization.
- (void)autoStretch;
@end
#import "AutoStretchButton.h"
@implementation AutoStretchButton
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
[self autoStretch];
}
return self;
}
- (id)initWithCoder:(NSCoder *)decoder {
self = [super initWithCoder:decoder];
if (self) {
[self autoStretch];
}
return self;
}
- (void)autoStretch {
for (UIControlState state = UIControlStateNormal; state <= UIControlStateSelected; state++) {
UIImage *image = [self backgroundImageForState:state];
if (image) {
UIImage *stretchedImage = [image
stretchableImageWithLeftCapWidth:image.size.width / 2
topCapHeight:image.size.height / 2];
[self setBackgroundImage:stretchedImage forState:state];
}
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment