Reputation: 2837
I have a UIButton object where I use a stretchable image for its background, so I can always have flexible button sizes.
The thing is I'd like to have a fixed height OF THE IMAGE (say 32px), but want to have a taller touchable area (Apple UI Guidelines say always at least 44px tall).
If I have a stretchable image in x, it unfortunately stretches in y as well. I'd like to tell the image not to stretch in y. Is this possible?
[EDIT] Yes, it is. Answering my own question:
Upvotes: 0
Views: 3166
Reputation: 2837
So, just to help others, I can answer my own question:
@interface StretchableXButton : UIButton
{
CGFloat imageHeight;
}
@property CGFloat imageHeight; // we need this later when we override an instance method
+ (id)buttonWithFrame:(CGRect)frame;
@end
and now the implementation:
@implementation StretchableXButton
@synthesize imageHeight;
+ (id)buttonWithFrame:(CGRect)frame
{
StretchableXButton *button = [super buttonWithType:UIButtonTypeCustom];
UIImage *normalImage = [UIImage imageNamed: @"ButtonBGNormal.png" ];
UIImage *highlightedImage = [UIImage imageNamed:@"ButtonBGHighlighted.png" ];
button.frame = frame;
button.imageHeight = normalImage.size.height; // we need him later in the method below
// make the images stretchable
normalImage = [normalImage stretchableImageWithLeftCapWidth:normalImage.size.width/2 topCapHeight:normalImage.size.height/2];
highlightedImage = [highlightedImage stretchableImageWithLeftCapWidth:normalImage.size.width/2 topCapHeight:normalImage.size.height/2];
button.backgroundColor = [UIColor clearColor];
// SET OTHER BUTTON PROPERTIES HERE (textLabel, fonts, etc.)
[button setBackgroundImage:normalImage forState:UIControlStateNormal];
[button setBackgroundImage:highlightedImage forState:UIControlStateHighlighted];
return button;
}
// THIS IS THE TRICK. We make the height of the background rect match the image.
-(CGRect)backgroundRectForBounds:(CGRect)bounds
{
CGRect bgRect = bounds;
bgRect.origin.y = (bounds.size.height - imageHeight)/2.0f;
bgRect.size.height = imageHeight;
return bgRect;
}
@end
Upvotes: 3